Merge branch 'main' into bug/module-resolution-refactor

This commit is contained in:
Andrew Branch
2022-11-09 15:15:49 -08:00
290 changed files with 9736 additions and 9729 deletions
+1 -4
View File
@@ -10,7 +10,7 @@
"es6": true
},
"plugins": [
"@typescript-eslint", "jsdoc", "no-null", "import", "eslint-plugin-local"
"@typescript-eslint", "no-null", "import", "eslint-plugin-local"
],
"rules": {
"@typescript-eslint/adjacent-overload-signatures": "error",
@@ -95,9 +95,6 @@
// eslint-plugin-no-null
"no-null/no-null": "error",
// eslint-plugin-jsdoc
"jsdoc/check-alignment": "error",
// eslint
"constructor-super": "error",
"curly": ["error", "multi-line"],
+145 -14
View File
@@ -6,12 +6,15 @@ import { task } from "hereby";
import _glob from "glob";
import util from "util";
import chalk from "chalk";
import { exec, readJson, getDiffTool, getDirSize, memoize, needsUpdate } from "./scripts/build/utils.mjs";
import { runConsoleTests, refBaseline, localBaseline, refRwcBaseline, localRwcBaseline } from "./scripts/build/tests.mjs";
import { exec, readJson, getDiffTool, getDirSize, memoize, needsUpdate, Debouncer, Deferred } from "./scripts/build/utils.mjs";
import { runConsoleTests, refBaseline, localBaseline, refRwcBaseline, localRwcBaseline, cleanTestDirs } from "./scripts/build/tests.mjs";
import { buildProject as realBuildProject, cleanProject, watchProject } from "./scripts/build/projects.mjs";
import { localizationDirectories } from "./scripts/build/localization.mjs";
import cmdLineOptions from "./scripts/build/options.mjs";
import esbuild from "esbuild";
import chokidar from "chokidar";
import { EventEmitter } from "events";
import { CancelToken } from "@esfx/canceltoken";
const glob = util.promisify(_glob);
@@ -141,7 +144,7 @@ const localize = task({
dependencies: [generateDiagnostics],
run: async () => {
if (needsUpdate(diagnosticMessagesGeneratedJson, generatedLCGFile)) {
return exec(process.execPath, ["scripts/generateLocalizedDiagnosticMessages.mjs", "src/loc/lcl", "built/local", diagnosticMessagesGeneratedJson], { ignoreExitCode: true });
await exec(process.execPath, ["scripts/generateLocalizedDiagnosticMessages.mjs", "src/loc/lcl", "built/local", diagnosticMessagesGeneratedJson], { ignoreExitCode: true });
}
}
});
@@ -191,6 +194,7 @@ async function runDtsBundler(entrypoint, output) {
* @property {string[]} [external]
* @property {boolean} [exportIsTsObject]
* @property {boolean} [treeShaking]
* @property {esbuild.WatchMode} [watchMode]
*/
function createBundler(entrypoint, outfile, taskOptions = {}) {
const getOptions = memoize(async () => {
@@ -269,7 +273,7 @@ function createBundler(entrypoint, outfile, taskOptions = {}) {
return {
build: async () => esbuild.build(await getOptions()),
watch: async () => esbuild.build({ ...await getOptions(), watch: true, logLevel: "info" }),
watch: async () => esbuild.build({ ...await getOptions(), watch: taskOptions.watchMode ?? true, logLevel: "info" }),
};
}
@@ -320,7 +324,7 @@ function entrypointBuildTask(options) {
const outDir = path.dirname(options.output);
await fs.promises.mkdir(outDir, { recursive: true });
const moduleSpecifier = path.relative(outDir, options.builtEntrypoint);
await fs.promises.writeFile(options.output, `module.exports = require("./${moduleSpecifier}")`);
await fs.promises.writeFile(options.output, `module.exports = require("./${moduleSpecifier.replace(/[\\/]/g, "/")}")`);
},
});
@@ -354,7 +358,7 @@ function entrypointBuildTask(options) {
}
const { main: tsc, watch: watchTsc } = entrypointBuildTask({
const { main: tsc, build: buildTsc, watch: watchTsc } = entrypointBuildTask({
name: "tsc",
description: "Builds the command-line compiler",
buildDeps: [generateDiagnostics],
@@ -386,13 +390,13 @@ export const dtsServices = task({
dependencies: [buildServices],
run: async () => {
if (needsUpdate("./built/local/typescript/tsconfig.tsbuildinfo", ["./built/local/typescript.d.ts", "./built/local/typescript.internal.d.ts"])) {
runDtsBundler("./built/local/typescript/typescript.d.ts", "./built/local/typescript.d.ts");
await runDtsBundler("./built/local/typescript/typescript.d.ts", "./built/local/typescript.d.ts");
}
},
});
const { main: tsserver, watch: watchTsserver } = entrypointBuildTask({
const { main: tsserver, build: buildTsserver, watch: watchTsserver } = entrypointBuildTask({
name: "tsserver",
description: "Builds the language server",
buildDeps: [generateDiagnostics],
@@ -410,10 +414,15 @@ const { main: tsserver, watch: watchTsserver } = entrypointBuildTask({
export { tsserver, watchTsserver };
const buildMin = task({
name: "build-min",
dependencies: [buildTsc, buildTsserver],
});
export const min = task({
name: "min",
description: "Builds only tsc and tsserver",
dependencies: [tsc, tsserver],
dependencies: [tsc, tsserver].concat(cmdLineOptions.typecheck ? [buildMin] : []),
});
export const watchMin = task({
@@ -456,7 +465,7 @@ export const dts = task({
const testRunner = "./built/local/run.js";
const watchTestsEmitter = new EventEmitter();
const { main: tests, watch: watchTests } = entrypointBuildTask({
name: "tests",
description: "Builds the test infrastructure",
@@ -477,6 +486,11 @@ const { main: tests, watch: watchTests } = entrypointBuildTask({
"mocha",
"ms",
],
watchMode: {
onRebuild() {
watchTestsEmitter.emit("rebuild");
}
}
},
});
export { tests, watchTests };
@@ -577,10 +591,15 @@ export const watchOtherOutputs = task({
dependencies: [watchCancellationToken, watchTypingsInstaller, watchWatchGuard, generateTypesMap, copyBuiltLocalDiagnosticMessages],
});
const buildLocal = task({
name: "build-local",
dependencies: [buildTsc, buildTsserver, buildServices, buildLssl]
});
export const local = task({
name: "local",
description: "Builds the full compiler and services",
dependencies: [localize, tsc, tsserver, services, lssl, otherOutputs, dts, buildSrc],
dependencies: [localize, tsc, tsserver, services, lssl, otherOutputs, dts].concat(cmdLineOptions.typecheck ? [buildLocal] : []),
});
export default local;
@@ -591,11 +610,12 @@ export const watchLocal = task({
dependencies: [localize, watchTsc, watchTsserver, watchServices, watchLssl, watchOtherOutputs, dts, watchSrc],
});
const runtestsDeps = [tests, generateLibs].concat(cmdLineOptions.typecheck ? [dts, buildSrc] : []);
export const runTests = task({
name: "runtests",
description: "Runs the tests using the built run.js file.",
dependencies: [tests, generateLibs, dts, buildSrc],
dependencies: runtestsDeps,
run: () => runConsoleTests(testRunner, "mocha-fivemat-progress-reporter", /*runInParallel*/ false),
});
// task("runtests").flags = {
@@ -614,10 +634,121 @@ export const runTests = task({
// " --shardId": "1-based ID of this shard (default: 1)",
// };
export const runTestsAndWatch = task({
name: "runtests-watch",
dependencies: [watchTests],
run: async () => {
if (!cmdLineOptions.tests && !cmdLineOptions.failed) {
console.log(chalk.redBright(`You must specifiy either --tests/-t or --failed to use 'runtests-watch'.`));
return;
}
let watching = true;
let running = true;
let lastTestChangeTimeMs = Date.now();
let testsChangedDeferred = /** @type {Deferred<void>} */(new Deferred());
let testsChangedCancelSource = CancelToken.source();
const testsChangedDebouncer = new Debouncer(1_000, endRunTests);
const testCaseWatcher = chokidar.watch([
"tests/cases/**/*.*",
"tests/lib/**/*.*",
"tests/projects/**/*.*",
], {
ignorePermissionErrors: true,
alwaysStat: true
});
process.on("SIGINT", endWatchMode);
process.on("SIGKILL", endWatchMode);
process.on("beforeExit", endWatchMode);
watchTestsEmitter.on("rebuild", onRebuild);
testCaseWatcher.on("all", onChange);
while (watching) {
const promise = testsChangedDeferred.promise;
const token = testsChangedCancelSource.token;
if (!token.signaled) {
running = true;
try {
await runConsoleTests(testRunner, "mocha-fivemat-progress-reporter", /*runInParallel*/ false, { token, watching: true });
}
catch {
// ignore
}
running = false;
}
if (watching) {
console.log(chalk.yellowBright(`[watch] test run complete, waiting for changes...`));
await promise;
}
}
function onRebuild() {
beginRunTests(testRunner);
}
/**
* @param {'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir'} eventName
* @param {string} path
* @param {fs.Stats | undefined} stats
*/
function onChange(eventName, path, stats) {
switch (eventName) {
case "change":
case "unlink":
case "unlinkDir":
break;
case "add":
case "addDir":
// skip files that are detected as 'add' but haven't actually changed since the last time tests were
// run.
if (stats && stats.mtimeMs <= lastTestChangeTimeMs) {
return;
}
break;
}
beginRunTests(path);
}
/**
* @param {string} path
*/
function beginRunTests(path) {
if (testsChangedDebouncer.empty) {
console.log(chalk.yellowBright(`[watch] tests changed due to '${path}', restarting...`));
if (running) {
console.log(chalk.yellowBright("[watch] aborting in-progress test run..."));
}
testsChangedCancelSource.cancel();
testsChangedCancelSource = CancelToken.source();
}
testsChangedDebouncer.enqueue();
}
function endRunTests() {
lastTestChangeTimeMs = Date.now();
testsChangedDeferred.resolve();
testsChangedDeferred = /** @type {Deferred<void>} */(new Deferred());
}
function endWatchMode() {
if (watching) {
watching = false;
console.log(chalk.yellowBright("[watch] exiting watch mode..."));
testsChangedCancelSource.cancel();
testCaseWatcher.close();
watchTestsEmitter.off("rebuild", onRebuild);
}
}
},
});
export const runTestsParallel = task({
name: "runtests-parallel",
description: "Runs all the tests in parallel using the built run.js file.",
dependencies: [tests, generateLibs, dts, buildSrc],
dependencies: runtestsDeps,
run: () => runConsoleTests(testRunner, "min", /*runInParallel*/ cmdLineOptions.workers > 1),
});
// task("runtests-parallel").flags = {
@@ -715,7 +846,7 @@ export const importDefinitelyTypedTests = task({
export const produceLKG = task({
name: "LKG",
description: "Makes a new LKG out of the built js files",
dependencies: [localize, tsc, tsserver, services, lssl, otherOutputs, dts],
dependencies: [local],
run: async () => {
if (!cmdLineOptions.bundle) {
throw new Error("LKG cannot be created when --bundle=false");
+68 -136
View File
@@ -13,6 +13,7 @@
"tsserver": "bin/tsserver"
},
"devDependencies": {
"@esfx/canceltoken": "^1.0.0",
"@octokit/rest": "latest",
"@types/chai": "latest",
"@types/fs-extra": "^9.0.13",
@@ -30,13 +31,13 @@
"azure-devops-node-api": "^11.2.0",
"chai": "latest",
"chalk": "^4.1.2",
"chokidar": "^3.5.3",
"del": "^6.1.1",
"diff": "^5.1.0",
"esbuild": "^0.15.13",
"eslint": "^8.22.0",
"eslint-formatter-autolinkable-stylish": "^1.2.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsdoc": "^39.3.6",
"eslint-plugin-local": "^1.0.0",
"eslint-plugin-no-null": "^1.0.2",
"fast-xml-parser": "^4.0.11",
@@ -57,20 +58,6 @@
"node": ">=4.2.0"
}
},
"node_modules/@es-joy/jsdoccomment": {
"version": "0.36.0",
"resolved": "https://registry.npmjs.org/@es-joy/jsdoccomment/-/jsdoccomment-0.36.0.tgz",
"integrity": "sha512-u0XZyvUF6Urb2cSivSXA8qXIpT/CxkHcdtZKoWusAzgzmsTWpg0F2FpWXsolHmMUyVY3dLWaoy+0ccJ5uf2QjA==",
"dev": true,
"dependencies": {
"comment-parser": "1.3.1",
"esquery": "^1.4.0",
"jsdoc-type-pratt-parser": "~3.1.0"
},
"engines": {
"node": "^14 || ^16 || ^17 || ^18 || ^19"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.15.13",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.15.13.tgz",
@@ -103,6 +90,38 @@
"node": ">=12"
}
},
"node_modules/@esfx/cancelable": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@esfx/cancelable/-/cancelable-1.0.0.tgz",
"integrity": "sha512-2dry/TuOT9ydpw86f396v09cyi/gLeGPIZSH4Gx+V/qKQaS/OXCRurCY+Cn8zkBfTAgFsjk9NE15d+LPo2kt9A==",
"dev": true,
"dependencies": {
"@esfx/disposable": "^1.0.0"
}
},
"node_modules/@esfx/canceltoken": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@esfx/canceltoken/-/canceltoken-1.0.0.tgz",
"integrity": "sha512-/TgdzC5O89w5v0TgwE2wcdtampWNAFOxzurCtb4RxYVr3m72yk3Bg82vMdznx+H9nnf28zVDR0PtpZO9FxmOkw==",
"dev": true,
"dependencies": {
"@esfx/cancelable": "^1.0.0",
"@esfx/disposable": "^1.0.0",
"tslib": "^2.4.0"
}
},
"node_modules/@esfx/canceltoken/node_modules/tslib": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz",
"integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==",
"dev": true
},
"node_modules/@esfx/disposable": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@esfx/disposable/-/disposable-1.0.0.tgz",
"integrity": "sha512-hu7EI+YxlEWEKrb2himbS13HNaq5mlUePASf99KeQqkiNeqiAZbKqG4w59uDcLZs8JrV3qJqS/NYib5ZMhbfTQ==",
"dev": true
},
"node_modules/@eslint/eslintrc": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.3.3.tgz",
@@ -1167,15 +1186,6 @@
"node": ">=8"
}
},
"node_modules/comment-parser": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.3.1.tgz",
"integrity": "sha512-B52sN2VNghyq5ofvUsqZjmk6YkihBX5vMSChmSK9v4ShjKf3Vk5Xcmgpw4o+iIgtrnM/u5FiMpz9VKb8lpBveA==",
"dev": true,
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -1963,27 +1973,6 @@
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"dev": true
},
"node_modules/eslint-plugin-jsdoc": {
"version": "39.6.2",
"resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-39.6.2.tgz",
"integrity": "sha512-dvgY/W7eUFoAIIiaWHERIMI61ZWqcz9YFjEeyTzdPlrZc3TY/3aZm5aB91NUoTLWYZmO/vFlYSuQi15tF7uE5A==",
"dev": true,
"dependencies": {
"@es-joy/jsdoccomment": "~0.36.0",
"comment-parser": "1.3.1",
"debug": "^4.3.4",
"escape-string-regexp": "^4.0.0",
"esquery": "^1.4.0",
"semver": "^7.3.8",
"spdx-expression-parse": "^3.0.1"
},
"engines": {
"node": "^14 || ^16 || ^17 || ^18 || ^19"
},
"peerDependencies": {
"eslint": "^7.0.0 || ^8.0.0"
}
},
"node_modules/eslint-plugin-local": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-local/-/eslint-plugin-local-1.0.0.tgz",
@@ -3051,15 +3040,6 @@
"js-yaml": "bin/js-yaml.js"
}
},
"node_modules/jsdoc-type-pratt-parser": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-3.1.0.tgz",
"integrity": "sha512-MgtD0ZiCDk9B+eI73BextfRrVQl0oyzRG8B2BjORts6jbunj4ScKPcyXGTbB6eXL4y9TzxCm6hyeLq/2ASzNdw==",
"dev": true,
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/json-schema-traverse": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
@@ -4010,28 +3990,6 @@
"source-map": "^0.6.0"
}
},
"node_modules/spdx-exceptions": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz",
"integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==",
"dev": true
},
"node_modules/spdx-expression-parse": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz",
"integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==",
"dev": true,
"dependencies": {
"spdx-exceptions": "^2.1.0",
"spdx-license-ids": "^3.0.0"
}
},
"node_modules/spdx-license-ids": {
"version": "3.0.12",
"resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.12.tgz",
"integrity": "sha512-rr+VVSXtRhO4OHbXUiAF7xW3Bo9DuuF6C5jH+q/x15j2jniycgKbxU09Hr0WqlSLUs4i4ltHGXqTe7VHclYWyA==",
"dev": true
},
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
@@ -4534,17 +4492,6 @@
}
},
"dependencies": {
"@es-joy/jsdoccomment": {
"version": "0.36.0",
"resolved": "https://registry.npmjs.org/@es-joy/jsdoccomment/-/jsdoccomment-0.36.0.tgz",
"integrity": "sha512-u0XZyvUF6Urb2cSivSXA8qXIpT/CxkHcdtZKoWusAzgzmsTWpg0F2FpWXsolHmMUyVY3dLWaoy+0ccJ5uf2QjA==",
"dev": true,
"requires": {
"comment-parser": "1.3.1",
"esquery": "^1.4.0",
"jsdoc-type-pratt-parser": "~3.1.0"
}
},
"@esbuild/android-arm": {
"version": "0.15.13",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.15.13.tgz",
@@ -4559,6 +4506,40 @@
"dev": true,
"optional": true
},
"@esfx/cancelable": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@esfx/cancelable/-/cancelable-1.0.0.tgz",
"integrity": "sha512-2dry/TuOT9ydpw86f396v09cyi/gLeGPIZSH4Gx+V/qKQaS/OXCRurCY+Cn8zkBfTAgFsjk9NE15d+LPo2kt9A==",
"dev": true,
"requires": {
"@esfx/disposable": "^1.0.0"
}
},
"@esfx/canceltoken": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@esfx/canceltoken/-/canceltoken-1.0.0.tgz",
"integrity": "sha512-/TgdzC5O89w5v0TgwE2wcdtampWNAFOxzurCtb4RxYVr3m72yk3Bg82vMdznx+H9nnf28zVDR0PtpZO9FxmOkw==",
"dev": true,
"requires": {
"@esfx/cancelable": "^1.0.0",
"@esfx/disposable": "^1.0.0",
"tslib": "^2.4.0"
},
"dependencies": {
"tslib": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz",
"integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==",
"dev": true
}
}
},
"@esfx/disposable": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@esfx/disposable/-/disposable-1.0.0.tgz",
"integrity": "sha512-hu7EI+YxlEWEKrb2himbS13HNaq5mlUePASf99KeQqkiNeqiAZbKqG4w59uDcLZs8JrV3qJqS/NYib5ZMhbfTQ==",
"dev": true
},
"@eslint/eslintrc": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.3.3.tgz",
@@ -5338,12 +5319,6 @@
}
}
},
"comment-parser": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.3.1.tgz",
"integrity": "sha512-B52sN2VNghyq5ofvUsqZjmk6YkihBX5vMSChmSK9v4ShjKf3Vk5Xcmgpw4o+iIgtrnM/u5FiMpz9VKb8lpBveA==",
"dev": true
},
"concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -5870,21 +5845,6 @@
}
}
},
"eslint-plugin-jsdoc": {
"version": "39.6.2",
"resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-39.6.2.tgz",
"integrity": "sha512-dvgY/W7eUFoAIIiaWHERIMI61ZWqcz9YFjEeyTzdPlrZc3TY/3aZm5aB91NUoTLWYZmO/vFlYSuQi15tF7uE5A==",
"dev": true,
"requires": {
"@es-joy/jsdoccomment": "~0.36.0",
"comment-parser": "1.3.1",
"debug": "^4.3.4",
"escape-string-regexp": "^4.0.0",
"esquery": "^1.4.0",
"semver": "^7.3.8",
"spdx-expression-parse": "^3.0.1"
}
},
"eslint-plugin-local": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-local/-/eslint-plugin-local-1.0.0.tgz",
@@ -6625,12 +6585,6 @@
"argparse": "^2.0.1"
}
},
"jsdoc-type-pratt-parser": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-3.1.0.tgz",
"integrity": "sha512-MgtD0ZiCDk9B+eI73BextfRrVQl0oyzRG8B2BjORts6jbunj4ScKPcyXGTbB6eXL4y9TzxCm6hyeLq/2ASzNdw==",
"dev": true
},
"json-schema-traverse": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
@@ -7288,28 +7242,6 @@
"source-map": "^0.6.0"
}
},
"spdx-exceptions": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz",
"integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==",
"dev": true
},
"spdx-expression-parse": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz",
"integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==",
"dev": true,
"requires": {
"spdx-exceptions": "^2.1.0",
"spdx-license-ids": "^3.0.0"
}
},
"spdx-license-ids": {
"version": "3.0.12",
"resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.12.tgz",
"integrity": "sha512-rr+VVSXtRhO4OHbXUiAF7xW3Bo9DuuF6C5jH+q/x15j2jniycgKbxU09Hr0WqlSLUs4i4ltHGXqTe7VHclYWyA==",
"dev": true
},
"string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+2 -1
View File
@@ -39,6 +39,7 @@
"!**/.gitattributes"
],
"devDependencies": {
"@esfx/canceltoken": "^1.0.0",
"@octokit/rest": "latest",
"@types/chai": "latest",
"@types/fs-extra": "^9.0.13",
@@ -56,13 +57,13 @@
"azure-devops-node-api": "^11.2.0",
"chai": "latest",
"chalk": "^4.1.2",
"chokidar": "^3.5.3",
"del": "^6.1.1",
"diff": "^5.1.0",
"esbuild": "^0.15.13",
"eslint": "^8.22.0",
"eslint-formatter-autolinkable-stylish": "^1.2.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsdoc": "^39.3.6",
"eslint-plugin-local": "^1.0.0",
"eslint-plugin-no-null": "^1.0.2",
"fast-xml-parser": "^4.0.11",
+4 -2
View File
@@ -4,7 +4,7 @@ import os from "os";
const ci = ["1", "true"].includes(process.env.CI ?? "");
const parsed = minimist(process.argv.slice(2), {
boolean: ["dirty", "light", "colors", "lkg", "soft", "fix", "failed", "keepFailed", "force", "built", "ci", "bundle"],
boolean: ["dirty", "light", "colors", "lkg", "soft", "fix", "failed", "keepFailed", "force", "built", "ci", "bundle", "typecheck"],
string: ["browser", "tests", "break", "host", "reporter", "stackTraceLimit", "timeout", "shards", "shardId"],
alias: {
/* eslint-disable quote-props */
@@ -39,7 +39,8 @@ const parsed = minimist(process.argv.slice(2), {
dirty: false,
built: false,
ci,
bundle: true
bundle: true,
typecheck: true,
}
});
@@ -80,5 +81,6 @@ export default options;
* @property {string} shardId
* @property {string} break
* @property {boolean} bundle
* @property {boolean} typecheck
*/
void 0;
+30 -4
View File
@@ -2,9 +2,11 @@ import del from "del";
import fs from "fs";
import os from "os";
import path from "path";
import chalk from "chalk";
import cmdLineOptions from "./options.mjs";
import { exec } from "./utils.mjs";
import { findUpFile, findUpRoot } from "./findUpDir.mjs";
import { CancelError } from "@esfx/canceltoken";
const mochaJs = path.resolve(findUpRoot(), "node_modules", "mocha", "bin", "_mocha");
export const localBaseline = "tests/baselines/local/";
@@ -17,8 +19,11 @@ export const localTest262Baseline = "internal/baselines/test262/local";
* @param {string} runJs
* @param {string} defaultReporter
* @param {boolean} runInParallel
* @param {object} options
* @param {import("@esfx/canceltoken").CancelToken} [options.token]
* @param {boolean} [options.watching]
*/
export async function runConsoleTests(runJs, defaultReporter, runInParallel) {
export async function runConsoleTests(runJs, defaultReporter, runInParallel, options = {}) {
let testTimeout = cmdLineOptions.timeout;
const tests = cmdLineOptions.tests;
const inspect = cmdLineOptions.break || cmdLineOptions.inspect;
@@ -31,7 +36,14 @@ export async function runConsoleTests(runJs, defaultReporter, runInParallel) {
const shards = +cmdLineOptions.shards || undefined;
const shardId = +cmdLineOptions.shardId || undefined;
if (!cmdLineOptions.dirty) {
if (options.watching) {
console.log(chalk.yellowBright(`[watch] cleaning test directories...`));
}
await cleanTestDirs();
if (options.token?.signaled) {
return;
}
}
if (fs.existsSync(testConfigFile)) {
@@ -56,6 +68,10 @@ export async function runConsoleTests(runJs, defaultReporter, runInParallel) {
testTimeout = 400000;
}
if (options.watching) {
console.log(chalk.yellowBright(`[watch] running tests...`));
}
if (tests || runners || light || testTimeout || taskConfigsFolder || keepFailed || shards || shardId) {
writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, testTimeout, keepFailed, shards, shardId);
}
@@ -114,7 +130,8 @@ export async function runConsoleTests(runJs, defaultReporter, runInParallel) {
try {
setNodeEnvToDevelopment();
const { exitCode } = await exec(process.execPath, args);
const { exitCode } = await exec(process.execPath, args, { token: options.token });
if (exitCode !== 0) {
errorStatus = exitCode;
error = new Error(`Process exited with status code ${errorStatus}.`);
@@ -132,8 +149,17 @@ export async function runConsoleTests(runJs, defaultReporter, runInParallel) {
await deleteTemporaryProjectOutput();
if (error !== undefined) {
process.exitCode = typeof errorStatus === "number" ? errorStatus : 2;
throw error;
if (error instanceof CancelError) {
throw error;
}
if (options.watching) {
console.error(`${chalk.redBright(error.name)}: ${error.message}`);
}
else {
process.exitCode = typeof errorStatus === "number" ? errorStatus : 2;
throw error;
}
}
}
+19 -3
View File
@@ -7,6 +7,7 @@ import which from "which";
import { spawn } from "child_process";
import assert from "assert";
import JSONC from "jsonc-parser";
import { CancelError } from "@esfx/canceltoken";
/**
* Executes the provided command once with the supplied arguments.
@@ -18,6 +19,7 @@ import JSONC from "jsonc-parser";
* @property {boolean} [ignoreExitCode]
* @property {boolean} [hidePrompt]
* @property {boolean} [waitForExit=true]
* @property {import("@esfx/canceltoken").CancelToken} [token]
*/
export async function exec(cmd, args, options = {}) {
return /**@type {Promise<{exitCode?: number}>}*/(new Promise((resolve, reject) => {
@@ -26,16 +28,24 @@ export async function exec(cmd, args, options = {}) {
if (!options.hidePrompt) console.log(`> ${chalk.green(cmd)} ${args.join(" ")}`);
const proc = spawn(which.sync(cmd), args, { stdio: waitForExit ? "inherit" : "ignore" });
if (waitForExit) {
const onCanceled = () => {
proc.kill();
};
const subscription = options.token?.subscribe(onCanceled);
proc.on("exit", exitCode => {
if (exitCode === 0 || ignoreExitCode) {
resolve({ exitCode: exitCode ?? undefined });
}
else {
reject(new Error(`Process exited with code: ${exitCode}`));
const reason = options.token?.signaled ? options.token.reason ?? new CancelError() :
new Error(`Process exited with code: ${exitCode}`);
reject(reason);
}
subscription?.unsubscribe();
});
proc.on("error", error => {
reject(error);
subscription?.unsubscribe();
});
}
else {
@@ -150,8 +160,12 @@ export function getDirSize(root) {
.reduce((acc, num) => acc + num, 0);
}
class Deferred {
/**
* @template T
*/
export class Deferred {
constructor() {
/** @type {Promise<T>} */
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
@@ -162,13 +176,15 @@ class Deferred {
export class Debouncer {
/**
* @param {number} timeout
* @param {() => Promise<any>} action
* @param {() => Promise<any> | void} action
*/
constructor(timeout, action) {
this._timeout = timeout;
this._action = action;
}
get empty() { return !this._deferred; }
enqueue() {
if (this._timer) {
clearTimeout(this._timer);
+89 -20
View File
@@ -13,9 +13,11 @@ module.exports = createRule({
internalCommentNotLastError: `@internal should only appear in final JSDoc comment for declaration.`,
multipleJSDocError: `Declaration has multiple JSDoc comments.`,
internalCommentOnParameterProperty: `@internal cannot appear on a JSDoc comment; use a declared property and an assignment in the constructor instead.`,
misalignedJSDocComment: `This JSDoc comment is misaligned.`,
},
schema: [],
type: "problem",
fixable: "whitespace",
},
defaultOptions: [],
@@ -24,6 +26,11 @@ module.exports = createRule({
const atInternal = "@internal";
const jsdocStart = "/**";
/** @type {(text: string) => boolean} */
function isJSDocText(text) {
return text.startsWith(jsdocStart);
}
/** @type {(c: TSESTree.Comment, indexInComment: number) => TSESTree.SourceLocation} */
const getAtInternalLoc = (c, indexInComment) => {
const line = c.loc.start.line;
@@ -51,7 +58,7 @@ module.exports = createRule({
};
/** @type {(node: TSESTree.Node) => void} */
const checkJSDocFormat = (node) => {
const checkDeclaration = (node) => {
const blockComments = sourceCode.getCommentsBefore(node).filter(c => c.type === "Block");
if (blockComments.length === 0) {
return;
@@ -63,7 +70,7 @@ module.exports = createRule({
const c = blockComments[i];
const rawComment = sourceCode.getText(c);
const isJSDoc = rawComment.startsWith(jsdocStart);
const isJSDoc = isJSDocText(rawComment);
if (isJSDoc && seenJSDoc) {
context.report({ messageId: "multipleJSDocError", node: c, loc: getJSDocStartLoc(c) });
}
@@ -86,25 +93,87 @@ module.exports = createRule({
}
};
/** @type {(node: TSESTree.Node) => void} */
const checkProgram = () => {
const comments = sourceCode.getAllComments();
for (const c of comments) {
if (c.type !== "Block") {
continue;
}
const rawComment = sourceCode.getText(c);
if (!isJSDocText(rawComment)) {
continue;
}
const expected = c.loc.start.column + 2;
const split = rawComment.split(/\r?\n/g);
for (let i = 1; i < split.length; i++) {
const line = split[i];
const match = /^ *\*/.exec(line);
if (!match) {
continue;
}
const actual = match[0].length;
const diff = actual - expected;
if (diff !== 0) {
const line = c.loc.start.line + i;
context.report({
messageId: "misalignedJSDocComment",
node: c,
loc: {
start: {
line,
column: 0,
},
end: {
line,
column: actual - 1,
}
},
fix: (fixer) => {
if (diff > 0) {
// Too many
const start = sourceCode.getIndexFromLoc({ line, column: expected - 1 });
return fixer.removeRange([start, start + diff]);
}
else {
// Too few
const start = sourceCode.getIndexFromLoc({ line, column: 0 });
return fixer.insertTextAfterRange([start, start], " ".repeat(-diff));
}
},
});
break;
}
}
}
};
return {
ClassDeclaration: checkJSDocFormat,
FunctionDeclaration: checkJSDocFormat,
TSEnumDeclaration: checkJSDocFormat,
TSModuleDeclaration: checkJSDocFormat,
VariableDeclaration: checkJSDocFormat,
TSInterfaceDeclaration: checkJSDocFormat,
TSTypeAliasDeclaration: checkJSDocFormat,
TSCallSignatureDeclaration: checkJSDocFormat,
ExportAllDeclaration: checkJSDocFormat,
ExportNamedDeclaration: checkJSDocFormat,
TSImportEqualsDeclaration: checkJSDocFormat,
TSNamespaceExportDeclaration: checkJSDocFormat,
TSConstructSignatureDeclaration: checkJSDocFormat,
ExportDefaultDeclaration: checkJSDocFormat,
TSPropertySignature: checkJSDocFormat,
TSIndexSignature: checkJSDocFormat,
TSMethodSignature: checkJSDocFormat,
TSParameterProperty: checkJSDocFormat,
Program: checkProgram,
ClassDeclaration: checkDeclaration,
FunctionDeclaration: checkDeclaration,
TSEnumDeclaration: checkDeclaration,
TSModuleDeclaration: checkDeclaration,
VariableDeclaration: checkDeclaration,
TSInterfaceDeclaration: checkDeclaration,
TSTypeAliasDeclaration: checkDeclaration,
TSCallSignatureDeclaration: checkDeclaration,
ExportAllDeclaration: checkDeclaration,
ExportNamedDeclaration: checkDeclaration,
TSImportEqualsDeclaration: checkDeclaration,
TSNamespaceExportDeclaration: checkDeclaration,
TSConstructSignatureDeclaration: checkDeclaration,
ExportDefaultDeclaration: checkDeclaration,
TSPropertySignature: checkDeclaration,
TSIndexSignature: checkDeclaration,
TSMethodSignature: checkDeclaration,
TSParameterProperty: checkDeclaration,
PropertyDefinition: checkDeclaration,
MethodDefinition: checkDeclaration,
};
},
});
+1 -1
View File
@@ -8,7 +8,7 @@ const os = require("os");
file?: string;
keepFailed?: boolean;
reporter?: Mocha.ReporterConstructor | keyof Mocha.reporters;
reporterOptions?: any; // TODO(jakebailey): what?
reporterOptions?: any;
}} ReporterOptions */
void 0;
+1 -1
View File
@@ -3,7 +3,7 @@ export = FailedTestsReporter;
file?: string;
keepFailed?: boolean;
reporter?: Mocha.ReporterConstructor | keyof Mocha.reporters;
reporterOptions?: any; // TODO(jakebailey): what?
reporterOptions?: any;
}} ReporterOptions */
/**
* .failed-tests reporter
+1 -7
View File
@@ -5,7 +5,6 @@
"project": "./tsconfig-base.json"
},
"rules": {
"@typescript-eslint/no-unnecessary-qualifier": "error",
"@typescript-eslint/no-unnecessary-type-assertion": "error",
"no-restricted-globals": ["error",
{ "name": "setTimeout" },
@@ -14,12 +13,7 @@
{ "name": "clearInterval" },
{ "name": "setImmediate" },
{ "name": "clearImmediate" },
{ "name": "performance" },
{ "name": "Iterator" },
{ "name": "Map" },
{ "name": "ReadonlyMap" },
{ "name": "Set" },
{ "name": "ReadonlySet" }
{ "name": "performance" }
]
},
"overrides": [
-3
View File
@@ -4,9 +4,6 @@
"module": "commonjs",
"types": [
"node"
],
"lib": [
"es6"
]
},
"include": ["**/*"]
+6 -6
View File
@@ -9,7 +9,7 @@ import {
createSymbolTable, Debug, Declaration, declarationNameToString, DeleteExpression, DestructuringAssignment,
DiagnosticCategory, DiagnosticMessage, DiagnosticRelatedInformation, Diagnostics, DiagnosticWithLocation,
DoStatement, DynamicNamedDeclaration, ElementAccessChain, ElementAccessExpression, EntityNameExpression,
EnumDeclaration, escapeLeadingUnderscores, ESMap, every, ExportAssignment, exportAssignmentIsAlias,
EnumDeclaration, escapeLeadingUnderscores, every, ExportAssignment, exportAssignmentIsAlias,
ExportDeclaration, ExportSpecifier, Expression, ExpressionStatement, findAncestor, FlowFlags, FlowLabel, FlowNode,
FlowReduceLabel, forEach, forEachChild, ForInOrOfStatement, ForStatement, FunctionDeclaration, FunctionExpression,
FunctionLikeDeclaration, GetAccessorDeclaration, getAssignedExpandoInitializer, getAssignmentDeclarationKind,
@@ -45,12 +45,12 @@ import {
isVariableDeclaration, isVariableDeclarationInitializedToBareOrAccessedRequire, isVariableStatement,
JSDocCallbackTag, JSDocClassTag, JSDocEnumTag, JSDocFunctionType, JSDocParameterTag, JSDocPropertyLikeTag,
JSDocSignature, JSDocTypedefTag, JSDocTypeLiteral, JsxAttribute, JsxAttributes, LabeledStatement, length,
LiteralLikeElementAccessExpression, Map, MappedTypeNode, MethodDeclaration, ModifierFlags, ModuleBlock,
LiteralLikeElementAccessExpression, MappedTypeNode, MethodDeclaration, ModifierFlags, ModuleBlock,
ModuleDeclaration, Mutable, NamespaceExportDeclaration, Node, NodeArray, NodeFlags, nodeHasName, nodeIsMissing,
nodeIsPresent, NonNullChain, NonNullExpression, NumericLiteral, objectAllocator, ObjectLiteralExpression,
OptionalChain, ParameterDeclaration, ParenthesizedExpression, Pattern, PatternAmbientModule, perfLogger,
PostfixUnaryExpression, PrefixUnaryExpression, PrivateIdentifier, PropertyAccessChain, PropertyAccessExpression,
PropertyDeclaration, PropertySignature, removeFileExtension, ReturnStatement, ScriptTarget, Set,
PropertyDeclaration, PropertySignature, removeFileExtension, ReturnStatement, ScriptTarget,
SetAccessorDeclaration, setParent, setParentRecursive, setValueDeclaration, ShorthandPropertyAssignment,
shouldPreserveConstEnums, SignatureDeclaration, skipParentheses, sliceAfter, some, SourceFile, SpreadElement,
Statement, StringLiteral, SwitchStatement, Symbol, SymbolFlags, symbolName, SymbolTable, SyntaxKind, TextRange,
@@ -76,7 +76,7 @@ interface ActiveLabel {
}
/** @internal */
export function getModuleInstanceState(node: ModuleDeclaration, visited?: ESMap<number, ModuleInstanceState | undefined>): ModuleInstanceState {
export function getModuleInstanceState(node: ModuleDeclaration, visited?: Map<number, ModuleInstanceState | undefined>): ModuleInstanceState {
if (node.body && !node.body.parent) {
// getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
setParent(node.body, node);
@@ -96,7 +96,7 @@ function getModuleInstanceStateCached(node: Node, visited = new Map<number, Modu
return result;
}
function getModuleInstanceStateWorker(node: Node, visited: ESMap<number, ModuleInstanceState | undefined>): ModuleInstanceState {
function getModuleInstanceStateWorker(node: Node, visited: Map<number, ModuleInstanceState | undefined>): ModuleInstanceState {
// A module is uninstantiated if it contains only
switch (node.kind) {
// 1. interface declarations, type alias declarations
@@ -168,7 +168,7 @@ function getModuleInstanceStateWorker(node: Node, visited: ESMap<number, ModuleI
return ModuleInstanceState.Instantiated;
}
function getModuleInstanceStateForAliasTarget(specifier: ExportSpecifier, visited: ESMap<number, ModuleInstanceState | undefined>) {
function getModuleInstanceStateForAliasTarget(specifier: ExportSpecifier, visited: Map<number, ModuleInstanceState | undefined>) {
const name = specifier.propertyName || specifier.name;
let p: Node | undefined = specifier.parent;
while (p) {
+12 -12
View File
@@ -7,12 +7,12 @@ import {
createBuildInfo, createGetCanonicalFileName, createProgram, CustomTransformers, Debug, Diagnostic,
DiagnosticCategory, DiagnosticMessageChain, DiagnosticRelatedInformation, DiagnosticWithLocation,
EmitAndSemanticDiagnosticsBuilderProgram, EmitOnly, EmitResult, emitSkippedWithNoDiagnostics, emptyArray,
ensurePathIsNonModuleName, ESMap, filterSemanticDiagnostics, forEach, forEachEntry, forEachKey, generateDjb2Hash,
ensurePathIsNonModuleName, filterSemanticDiagnostics, forEach, forEachEntry, forEachKey, generateDjb2Hash,
GetCanonicalFileName, getDirectoryPath, getEmitDeclarations, getNormalizedAbsolutePath, getOptionsNameMap,
getOwnKeys, getRelativePathFromDirectory, getTsBuildInfoEmitOutputFilePath, handleNoEmitOptions, isArray,
isDeclarationFileName, isJsonSourceFile, isNumber, isString, map, Map, mapDefined, maybeBind, noop, notImplemented,
outFile, Path, Program, ProjectReference, ReadBuildProgramHost, ReadonlyCollection, ReadonlyESMap, ReadonlySet,
returnFalse, returnUndefined, SemanticDiagnosticsBuilderProgram, Set, skipTypeChecking, some, SourceFile,
isDeclarationFileName, isJsonSourceFile, isNumber, isString, map, mapDefined, maybeBind, noop, notImplemented,
outFile, Path, Program, ProjectReference, ReadBuildProgramHost, ReadonlyCollection,
returnFalse, returnUndefined, SemanticDiagnosticsBuilderProgram, skipTypeChecking, some, SourceFile,
sourceFileMayBeEmitted, SourceMapEmitResult, toPath, tryAddToSet, WriteFileCallback, WriteFileCallbackData,
} from "./_namespaces/ts";
@@ -51,7 +51,7 @@ export interface ReusableBuilderProgramState extends BuilderState {
/**
* Cache of bind and check diagnostics for files with their Path being the key
*/
semanticDiagnosticsPerFile?: ESMap<Path, readonly ReusableDiagnostic[] | readonly Diagnostic[]> | undefined;
semanticDiagnosticsPerFile?: Map<Path, readonly ReusableDiagnostic[] | readonly Diagnostic[]> | undefined;
/**
* The map has key by source file's path that has been changed
*/
@@ -67,7 +67,7 @@ export interface ReusableBuilderProgramState extends BuilderState {
/**
* Files pending to be emitted
*/
affectedFilesPendingEmit?: ReadonlyESMap<Path, BuilderFileEmit>;
affectedFilesPendingEmit?: ReadonlyMap<Path, BuilderFileEmit>;
/**
* emitKind pending for a program with --out
*/
@@ -79,7 +79,7 @@ export interface ReusableBuilderProgramState extends BuilderState {
/**
* Hash of d.ts emitted for the file, use to track when emit of d.ts changes
*/
emitSignatures?: ESMap<Path, EmitSignature>;
emitSignatures?: Map<Path, EmitSignature>;
/**
* Hash of d.ts emit with --out
*/
@@ -118,7 +118,7 @@ export interface BuilderProgramState extends BuilderState, ReusableBuilderProgra
/**
* Cache of bind and check diagnostics for files with their Path being the key
*/
semanticDiagnosticsPerFile: ESMap<Path, readonly Diagnostic[]> | undefined;
semanticDiagnosticsPerFile: Map<Path, readonly Diagnostic[]> | undefined;
/**
* The map has key by source file's path that has been changed
*/
@@ -154,7 +154,7 @@ export interface BuilderProgramState extends BuilderState, ReusableBuilderProgra
/**
* Files pending to be emitted
*/
affectedFilesPendingEmit?: ESMap<Path, BuilderFileEmit>;
affectedFilesPendingEmit?: Map<Path, BuilderFileEmit>;
/**
* true if build info is emitted
*/
@@ -162,7 +162,7 @@ export interface BuilderProgramState extends BuilderState, ReusableBuilderProgra
/**
* Already seen emitted files
*/
seenEmittedFiles: ESMap<Path, BuilderFileEmit> | undefined;
seenEmittedFiles: Map<Path, BuilderFileEmit> | undefined;
/** Stores list of files that change signature during emit - test only */
filesChangingSignature?: Set<Path>;
}
@@ -954,7 +954,7 @@ function getBuildInfo(state: BuilderProgramState, getCanonicalFileName: GetCanon
}
let fileIdsList: (readonly ProgramBuildInfoFileId[])[] | undefined;
let fileNamesToFileIdListId: ESMap<string, ProgramBuildInfoFileIdListId> | undefined;
let fileNamesToFileIdListId: Map<string, ProgramBuildInfoFileIdListId> | undefined;
let emitSignatures: ProgramBuildInfoEmitSignature[] | undefined;
const fileInfos = arrayFrom(state.fileInfos.entries(), ([key, value]): ProgramMultiFileEmitBuildInfoFileInfo => {
// Ensure fileId
@@ -1733,7 +1733,7 @@ export function getBuildInfoFileVersionMap(
program: ProgramBuildInfo,
buildInfoPath: string,
host: Pick<ReadBuildProgramHost, "useCaseSensitiveFileNames" | "getCurrentDirectory">
): ESMap<Path, string> {
): Map<Path, string> {
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
const fileInfos = new Map<Path, string>();
+9 -9
View File
@@ -1,9 +1,9 @@
import {
arrayFrom, CancellationToken, computeSignatureWithDiagnostics, CustomTransformers, Debug, EmitOutput, emptyArray,
ESMap, ExportedModulesFromDeclarationEmit, GetCanonicalFileName, getDirectoryPath, getSourceFileOfNode,
ExportedModulesFromDeclarationEmit, GetCanonicalFileName, getDirectoryPath, getSourceFileOfNode,
isDeclarationFileName, isExternalOrCommonJsModule, isGlobalScopeAugmentation, isJsonSourceFile,
isModuleWithStringLiteralName, isStringLiteral, Iterator, Map, mapDefined, mapDefinedIterator, ModuleDeclaration,
ModuleKind, outFile, OutputFile, Path, Program, ReadonlySet, Set, some, SourceFile, StringLiteralLike, Symbol,
isModuleWithStringLiteralName, isStringLiteral, mapDefined, mapDefinedIterator, ModuleDeclaration,
ModuleKind, outFile, OutputFile, Path, Program, some, SourceFile, StringLiteralLike, Symbol,
toPath, TypeChecker,
} from "./_namespaces/ts";
@@ -23,7 +23,7 @@ export interface BuilderState {
/**
* Information of the file eg. its version, signature etc
*/
fileInfos: ESMap<Path, BuilderState.FileInfo>;
fileInfos: Map<Path, BuilderState.FileInfo>;
/**
* Contains the map of ReferencedSet=Referenced files of the file if module emit is enabled
* Otherwise undefined
@@ -52,11 +52,11 @@ export interface BuilderState {
/**
* Stores signatures before before the update till affected file is commited
*/
oldSignatures?: ESMap<Path, string | false>;
oldSignatures?: Map<Path, string | false>;
/**
* Stores exportedModulesMap before the update till affected file is commited
*/
oldExportedModulesMap?: ESMap<Path, ReadonlySet<Path> | false>;
oldExportedModulesMap?: Map<Path, ReadonlySet<Path> | false>;
/**
* Cache of all files excluding default library file for the current program
*/
@@ -90,7 +90,7 @@ export namespace BuilderState {
}
export function createManyToManyPathMap(): ManyToManyPathMap {
function create(forward: ESMap<Path, ReadonlySet<Path>>, reverse: ESMap<Path, Set<Path>>, deleted: Set<Path> | undefined): ManyToManyPathMap {
function create(forward: Map<Path, ReadonlySet<Path>>, reverse: Map<Path, Set<Path>>, deleted: Set<Path> | undefined): ManyToManyPathMap {
const map: ManyToManyPathMap = {
getKeys: v => reverse.get(v),
getValues: k => forward.get(k),
@@ -136,7 +136,7 @@ export namespace BuilderState {
return create(new Map<Path, Set<Path>>(), new Map<Path, Set<Path>>(), /*deleted*/ undefined);
}
function addToMultimap<K, V>(map: ESMap<K, Set<V>>, k: K, v: V): void {
function addToMultimap<K, V>(map: Map<K, Set<V>>, k: K, v: V): void {
let set = map.get(k);
if (!set) {
set = new Set<V>();
@@ -145,7 +145,7 @@ export namespace BuilderState {
set.add(v);
}
function deleteFromMultimap<K, V>(map: ESMap<K, Set<V>>, k: K, v: V): boolean {
function deleteFromMultimap<K, V>(map: Map<K, Set<V>>, k: K, v: V): boolean {
const set = map.get(k);
if (set?.delete(v)) {
+473 -471
View File
File diff suppressed because it is too large Load Diff
+29 -29
View File
@@ -4,7 +4,7 @@ import {
CommandLineOptionOfListType, CompilerOptions, CompilerOptionsValue, ConfigFileSpecs, containsPath,
convertToRelativePath, createCompilerDiagnostic, createDiagnosticForNodeInSourceFile, createGetCanonicalFileName,
Debug, Diagnostic, DiagnosticMessage, Diagnostics, DidYouMeanOptionsDiagnostics, directorySeparator, emptyArray,
endsWith, ensureTrailingDirectorySeparator, ESMap, every, Expression, extend, Extension, FileExtensionInfo,
endsWith, ensureTrailingDirectorySeparator, every, Expression, extend, Extension, FileExtensionInfo,
fileExtensionIs, fileExtensionIsOneOf, filter, filterMutate, find, findIndex, firstDefined, flatten, forEach,
forEachEntry, getBaseFileName, getDirectoryPath, getEntries, getFileMatcherPatterns, getLocaleSpecificMessage,
getNormalizedAbsolutePath, getRegexFromPattern, getRegularExpressionForWildcard, getRegularExpressionsForWildcards,
@@ -12,7 +12,7 @@ import {
getSupportedExtensionsWithJsonIfResolveJsonModule, getTextOfPropertyName, getTsConfigPropArray,
getTsConfigPropArrayElementValue, hasExtension, hasProperty, ImportsNotUsedAsValues, isArray,
isArrayLiteralExpression, isComputedNonLiteralName, isImplicitGlob, isObjectLiteralExpression, isRootedDiskPath,
isString, isStringDoubleQuoted, isStringLiteral, JsonSourceFile, JsxEmit, length, map, Map, mapDefined, mapIterator,
isString, isStringDoubleQuoted, isStringLiteral, JsonSourceFile, JsxEmit, length, map, mapDefined, mapIterator,
MapLike, ModuleDetectionKind, ModuleKind, ModuleResolutionKind, NewLineKind, Node, NodeArray,
nodeModuleNameResolver, normalizePath, normalizeSlashes, NumericLiteral, ObjectLiteralExpression, ParseConfigHost,
ParsedCommandLine, parseJsonText, Path, PollingWatchKind, PrefixUnaryExpression, ProjectReference, PropertyName,
@@ -1490,8 +1490,8 @@ export const typeAcquisitionDeclarations: CommandLineOption[] = [
/** @internal */
export interface OptionsNameMap {
optionsNameMap: ESMap<string, CommandLineOption>;
shortOptionNames: ESMap<string, string>;
optionsNameMap: Map<string, CommandLineOption>;
shortOptionNames: Map<string, string>;
}
/** @internal */
@@ -1885,7 +1885,7 @@ export function getParsedCommandLineOfConfigFile(
configFileName: string,
optionsToExtend: CompilerOptions | undefined,
host: ParseConfigFileHost,
extendedConfigCache?: Map<ExtendedConfigCacheEntry>,
extendedConfigCache?: Map<string, ExtendedConfigCacheEntry>,
watchOptionsToExtend?: WatchOptions,
extraFileExtensions?: readonly FileExtensionInfo[],
): ParsedCommandLine | undefined {
@@ -1978,15 +1978,15 @@ const watchOptionsDidYouMeanDiagnostics: ParseCommandLineWorkerDiagnostics = {
optionTypeMismatchDiagnostic: Diagnostics.Watch_option_0_requires_a_value_of_type_1
};
let commandLineCompilerOptionsMapCache: ESMap<string, CommandLineOption>;
let commandLineCompilerOptionsMapCache: Map<string, CommandLineOption>;
function getCommandLineCompilerOptionsMap() {
return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(optionDeclarations));
}
let commandLineWatchOptionsMapCache: ESMap<string, CommandLineOption>;
let commandLineWatchOptionsMapCache: Map<string, CommandLineOption>;
function getCommandLineWatchOptionsMap() {
return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(optionsForWatch));
}
let commandLineTypeAcquisitionMapCache: ESMap<string, CommandLineOption>;
let commandLineTypeAcquisitionMapCache: Map<string, CommandLineOption>;
function getCommandLineTypeAcquisitionMap() {
return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(typeAcquisitionDeclarations));
}
@@ -2152,13 +2152,13 @@ export function convertToObjectWorker(
return convertPropertyValueToJson(rootExpression, knownRootOptions);
function isRootOptionMap(knownOptions: ESMap<string, CommandLineOption> | undefined) {
function isRootOptionMap(knownOptions: Map<string, CommandLineOption> | undefined) {
return knownRootOptions && (knownRootOptions as TsConfigOnlyOption).elementOptions === knownOptions;
}
function convertObjectLiteralExpressionToJson(
node: ObjectLiteralExpression,
knownOptions: ESMap<string, CommandLineOption> | undefined,
knownOptions: Map<string, CommandLineOption> | undefined,
extraKeyDiagnostics: DidYouMeanOptionsDiagnostics | undefined,
parentOption: string | undefined
): any {
@@ -2430,7 +2430,7 @@ export function convertToTSConfig(configParseResult: ParsedCommandLine, configFi
}
/** @internal */
export function optionMapToObject(optionMap: ESMap<string, CompilerOptionsValue>): object {
export function optionMapToObject(optionMap: Map<string, CompilerOptionsValue>): object {
return {
...arrayFrom(optionMap.entries()).reduce((prev, cur) => ({ ...prev, [cur[0]]: cur[1] }), {}),
};
@@ -2460,7 +2460,7 @@ function matchesSpecs(path: string, includeSpecs: readonly string[] | undefined,
return returnTrue;
}
function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): ESMap<string, string | number> | undefined {
function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): Map<string, string | number> | undefined {
if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
// this is of a type CommandLineOptionOfPrimitiveType
return undefined;
@@ -2474,7 +2474,7 @@ function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption
}
/** @internal */
export function getNameOfCompilerOptionValue(value: CompilerOptionsValue, customTypeMap: ESMap<string, string | number>): string | undefined {
export function getNameOfCompilerOptionValue(value: CompilerOptionsValue, customTypeMap: Map<string, string | number>): string | undefined {
// There is a typeMap associated with this command-line option so use it to map value back to its name
return forEachEntry(customTypeMap, (mapValue, key) => {
if (mapValue === value) {
@@ -2487,7 +2487,7 @@ export function getNameOfCompilerOptionValue(value: CompilerOptionsValue, custom
export function serializeCompilerOptions(
options: CompilerOptions,
pathOptions?: { configFilePath: string, useCaseSensitiveFileNames: boolean }
): ESMap<string, CompilerOptionsValue> {
): Map<string, CompilerOptionsValue> {
return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
}
@@ -2499,7 +2499,7 @@ function serializeOptionBaseObject(
options: OptionsBase,
{ optionsNameMap }: OptionsNameMap,
pathOptions?: { configFilePath: string, useCaseSensitiveFileNames: boolean }
): ESMap<string, CompilerOptionsValue> {
): Map<string, CompilerOptionsValue> {
const result = new Map<string, CompilerOptionsValue>();
const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
@@ -2553,7 +2553,7 @@ export function getCompilerOptionsDiffValue(options: CompilerOptions, newLine: s
function getOverwrittenDefaultOptions() {
const result: string[] = [];
const tab = makePadding(2);
const tab = makePadding(2);
commandOptionsWithoutBuild.forEach(cmd => {
if (!compilerOptionsMap.has(cmd.name)) {
return;
@@ -2576,7 +2576,7 @@ export function getCompilerOptionsDiffValue(options: CompilerOptions, newLine: s
* Get the compiler options to be written into the tsconfig.json.
* @param options commandlineOptions to be included in the compileOptions.
*/
function getSerializedCompilerOption(options: CompilerOptions): ESMap<string, CompilerOptionsValue> {
function getSerializedCompilerOption(options: CompilerOptions): Map<string, CompilerOptionsValue> {
const compilerOptions = extend(options, defaultInitCompilerOptions);
return serializeCompilerOptions(compilerOptions);
}
@@ -2717,7 +2717,7 @@ function convertToOptionValueWithAbsolutePaths(option: CommandLineOption | undef
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map<ExtendedConfigCacheEntry>, existingWatchOptions?: WatchOptions): ParsedCommandLine {
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map<string, ExtendedConfigCacheEntry>, existingWatchOptions?: WatchOptions): ParsedCommandLine {
return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
}
@@ -2728,7 +2728,7 @@ export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, bas
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map<ExtendedConfigCacheEntry>, existingWatchOptions?: WatchOptions): ParsedCommandLine {
export function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map<string, ExtendedConfigCacheEntry>, existingWatchOptions?: WatchOptions): ParsedCommandLine {
tracing?.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { path: sourceFile.fileName });
const result = parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
tracing?.pop();
@@ -2774,7 +2774,7 @@ function parseJsonConfigFileContentWorker(
configFileName?: string,
resolutionStack: Path[] = [],
extraFileExtensions: readonly FileExtensionInfo[] = [],
extendedConfigCache?: ESMap<string, ExtendedConfigCacheEntry>
extendedConfigCache?: Map<string, ExtendedConfigCacheEntry>
): ParsedCommandLine {
Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
const errors: Diagnostic[] = [];
@@ -2996,7 +2996,7 @@ function parseConfig(
configFileName: string | undefined,
resolutionStack: string[],
errors: Push<Diagnostic>,
extendedConfigCache?: ESMap<string, ExtendedConfigCacheEntry>
extendedConfigCache?: Map<string, ExtendedConfigCacheEntry>
): ParsedTsconfig {
basePath = normalizeSlashes(basePath);
const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath);
@@ -3024,7 +3024,7 @@ function parseConfig(
if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
const baseRaw = extendedConfig.raw;
const raw = ownConfig.raw;
let relativeDifference: string | undefined ;
let relativeDifference: string | undefined;
const setPropertyInRawIfNotUndefined = (propertyName: string) => {
if (!raw[propertyName] && baseRaw[propertyName]) {
raw[propertyName] = map(baseRaw[propertyName], (path: string) => isRootedDiskPath(path) ? path : combinePaths(
@@ -3202,7 +3202,7 @@ function getExtendedConfig(
host: ParseConfigHost,
resolutionStack: string[],
errors: Push<Diagnostic>,
extendedConfigCache?: ESMap<string, ExtendedConfigCacheEntry>
extendedConfigCache?: Map<string, ExtendedConfigCacheEntry>
): ParsedTsconfig | undefined {
const path = host.useCaseSensitiveFileNames ? extendedConfigPath : toFileNameLowerCase(extendedConfigPath);
let value: ExtendedConfigCacheEntry | undefined;
@@ -3290,11 +3290,11 @@ function convertWatchOptionsFromJsonWorker(jsonOptions: any, basePath: string, e
return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
}
function convertOptionsFromJson(optionsNameMap: ESMap<string, CommandLineOption>, jsonOptions: any, basePath: string,
function convertOptionsFromJson(optionsNameMap: Map<string, CommandLineOption>, jsonOptions: any, basePath: string,
defaultOptions: undefined, diagnostics: DidYouMeanOptionsDiagnostics, errors: Push<Diagnostic>): WatchOptions | undefined;
function convertOptionsFromJson(optionsNameMap: ESMap<string, CommandLineOption>, jsonOptions: any, basePath: string,
function convertOptionsFromJson(optionsNameMap: Map<string, CommandLineOption>, jsonOptions: any, basePath: string,
defaultOptions: CompilerOptions | TypeAcquisition, diagnostics: DidYouMeanOptionsDiagnostics, errors: Push<Diagnostic>): CompilerOptions | TypeAcquisition;
function convertOptionsFromJson(optionsNameMap: ESMap<string, CommandLineOption>, jsonOptions: any, basePath: string,
function convertOptionsFromJson(optionsNameMap: Map<string, CommandLineOption>, jsonOptions: any, basePath: string,
defaultOptions: CompilerOptions | TypeAcquisition | WatchOptions | undefined, diagnostics: DidYouMeanOptionsDiagnostics, errors: Push<Diagnostic>) {
if (!jsonOptions) {
@@ -3318,7 +3318,7 @@ export function convertJsonOption(opt: CommandLineOption, value: any, basePath:
if (isCompilerOptionsValue(opt, value)) {
const optType = opt.type;
if (optType === "list" && isArray(value)) {
return convertJsonOptionOfListType(opt , value, basePath, errors);
return convertJsonOptionOfListType(opt, value, basePath, errors);
}
else if (!isString(optType)) {
return convertJsonOptionOfCustomType(opt as CommandLineOptionOfCustomType, value as string, errors);
@@ -3687,7 +3687,7 @@ function getWildcardDirectoryFromSpec(spec: string, useCaseSensitiveFileNames: b
*
* @param file The path to the file.
*/
function hasFileWithHigherPriorityExtension(file: string, literalFiles: ESMap<string, string>, wildcardFiles: ESMap<string, string>, extensions: readonly string[][], keyMapper: (value: string) => string) {
function hasFileWithHigherPriorityExtension(file: string, literalFiles: Map<string, string>, wildcardFiles: Map<string, string>, extensions: readonly string[][], keyMapper: (value: string) => string) {
const extensionGroup = forEach(extensions, group => fileExtensionIsOneOf(file, group) ? group : undefined);
if (!extensionGroup) {
return false;
@@ -3717,7 +3717,7 @@ function hasFileWithHigherPriorityExtension(file: string, literalFiles: ESMap<st
*
* @param file The path to the file.
*/
function removeWildcardFilesWithLowerPriorityExtension(file: string, wildcardFiles: ESMap<string, string>, extensions: readonly string[][], keyMapper: (value: string) => string) {
function removeWildcardFilesWithLowerPriorityExtension(file: string, wildcardFiles: Map<string, string>, extensions: readonly string[][], keyMapper: (value: string) => string) {
const extensionGroup = forEach(extensions, group => fileExtensionIsOneOf(file, group) ? group : undefined);
if (!extensionGroup) {
return;
+42 -32
View File
@@ -1,26 +1,26 @@
import {
__String, CharacterCodes, Comparer, Comparison, Debug, EqualityComparer, ESMap, isWhiteSpaceLike, Iterator, Map,
MapLike, Push, Queue, ReadonlyESMap, ReadonlySet, Set, SortedArray, SortedReadonlyArray, TextSpan,
__String, CharacterCodes, Comparer, Comparison, Debug, EqualityComparer, isWhiteSpaceLike,
MapLike, Push, Queue, SortedArray, SortedReadonlyArray, TextSpan,
UnderscoreEscapedMap,
} from "./_namespaces/ts";
/** @internal */
export function getIterator<I extends readonly any[] | ReadonlySet<any> | ReadonlyESMap<any, any> | undefined>(iterable: I): Iterator<
I extends ReadonlyESMap<infer K, infer V> ? [K, V] :
export function getIterator<I extends readonly any[] | ReadonlySet<any> | ReadonlyMap<any, any> | undefined>(iterable: I): Iterator<
I extends ReadonlyMap<infer K, infer V> ? [K, V] :
I extends ReadonlySet<infer T> ? T :
I extends readonly (infer T)[] ? T :
I extends undefined ? undefined :
never>;
/** @internal */
export function getIterator<K, V>(iterable: ReadonlyESMap<K, V>): Iterator<[K, V]>;
export function getIterator<K, V>(iterable: ReadonlyMap<K, V>): Iterator<[K, V]>;
/** @internal */
export function getIterator<K, V>(iterable: ReadonlyESMap<K, V> | undefined): Iterator<[K, V]> | undefined;
export function getIterator<K, V>(iterable: ReadonlyMap<K, V> | undefined): Iterator<[K, V]> | undefined;
/** @internal */
export function getIterator<T>(iterable: readonly T[] | ReadonlySet<T>): Iterator<T>;
/** @internal */
export function getIterator<T>(iterable: readonly T[] | ReadonlySet<T> | undefined): Iterator<T> | undefined;
/** @internal */
export function getIterator(iterable: readonly any[] | ReadonlySet<any> | ReadonlyESMap<any, any> | undefined): Iterator<any> | undefined {
export function getIterator(iterable: readonly any[] | ReadonlySet<any> | ReadonlyMap<any, any> | undefined): Iterator<any> | undefined {
if (iterable) {
if (isArray(iterable)) return arrayIterator(iterable);
if (iterable instanceof Map) return iterable.entries();
@@ -32,7 +32,7 @@ export function getIterator(iterable: readonly any[] | ReadonlySet<any> | Readon
/** @internal */
export const emptyArray: never[] = [] as never[];
/** @internal */
export const emptyMap: ReadonlyESMap<never, never> = new Map<never, never>();
export const emptyMap: ReadonlyMap<never, never> = new Map<never, never>();
/** @internal */
export const emptySet: ReadonlySet<never> = new Set<never>();
@@ -147,7 +147,7 @@ export function zipToIterator<T, U>(arrayA: readonly T[], arrayB: readonly U[]):
}
/** @internal */
export function zipToMap<K, V>(keys: readonly K[], values: readonly V[]): ESMap<K, V> {
export function zipToMap<K, V>(keys: readonly K[], values: readonly V[]): Map<K, V> {
Debug.assert(keys.length === values.length);
const map = new Map<K, V>();
for (let i = 0; i < keys.length; ++i) {
@@ -608,11 +608,11 @@ export function mapDefinedIterator<T, U>(iter: Iterator<T>, mapFn: (x: T) => U |
}
/** @internal */
export function mapDefinedEntries<K1, V1, K2, V2>(map: ReadonlyESMap<K1, V1>, f: (key: K1, value: V1) => readonly [K2, V2] | undefined): ESMap<K2, V2>;
export function mapDefinedEntries<K1, V1, K2, V2>(map: ReadonlyMap<K1, V1>, f: (key: K1, value: V1) => readonly [K2, V2] | undefined): Map<K2, V2>;
/** @internal */
export function mapDefinedEntries<K1, V1, K2, V2>(map: ReadonlyESMap<K1, V1> | undefined, f: (key: K1, value: V1) => readonly [K2 | undefined, V2 | undefined] | undefined): ESMap<K2, V2> | undefined;
export function mapDefinedEntries<K1, V1, K2, V2>(map: ReadonlyMap<K1, V1> | undefined, f: (key: K1, value: V1) => readonly [K2 | undefined, V2 | undefined] | undefined): Map<K2, V2> | undefined;
/** @internal */
export function mapDefinedEntries<K1, V1, K2, V2>(map: ReadonlyESMap<K1, V1> | undefined, f: (key: K1, value: V1) => readonly [K2 | undefined, V2 | undefined] | undefined): ESMap<K2, V2> | undefined {
export function mapDefinedEntries<K1, V1, K2, V2>(map: ReadonlyMap<K1, V1> | undefined, f: (key: K1, value: V1) => readonly [K2 | undefined, V2 | undefined] | undefined): Map<K2, V2> | undefined {
if (!map) {
return undefined;
}
@@ -650,7 +650,7 @@ export function mapDefinedValues<V1, V2>(set: ReadonlySet<V1> | undefined, f: (v
}
/** @internal */
export function getOrUpdate<K, V>(map: ESMap<K, V>, key: K, callback: () => V) {
export function getOrUpdate<K, V>(map: Map<K, V>, key: K, callback: () => V) {
if (map.has(key)) {
return map.get(key)!;
}
@@ -737,11 +737,11 @@ export function spanMap<T, K, U>(array: readonly T[] | undefined, keyfn: (x: T,
}
/** @internal */
export function mapEntries<K1, V1, K2, V2>(map: ReadonlyESMap<K1, V1>, f: (key: K1, value: V1) => readonly [K2, V2]): ESMap<K2, V2>;
export function mapEntries<K1, V1, K2, V2>(map: ReadonlyMap<K1, V1>, f: (key: K1, value: V1) => readonly [K2, V2]): Map<K2, V2>;
/** @internal */
export function mapEntries<K1, V1, K2, V2>(map: ReadonlyESMap<K1, V1> | undefined, f: (key: K1, value: V1) => readonly [K2, V2]): ESMap<K2, V2> | undefined;
export function mapEntries<K1, V1, K2, V2>(map: ReadonlyMap<K1, V1> | undefined, f: (key: K1, value: V1) => readonly [K2, V2]): Map<K2, V2> | undefined;
/** @internal */
export function mapEntries<K1, V1, K2, V2>(map: ReadonlyESMap<K1, V1> | undefined, f: (key: K1, value: V1) => readonly [K2, V2]): ESMap<K2, V2> | undefined {
export function mapEntries<K1, V1, K2, V2>(map: ReadonlyMap<K1, V1> | undefined, f: (key: K1, value: V1) => readonly [K2, V2]): Map<K2, V2> | undefined {
if (!map) {
return undefined;
}
@@ -1569,15 +1569,15 @@ export function equalOwnProperties<T>(left: MapLike<T> | undefined, right: MapLi
*
* @internal
*/
export function arrayToMap<K, V>(array: readonly V[], makeKey: (value: V) => K | undefined): ESMap<K, V>;
export function arrayToMap<K, V>(array: readonly V[], makeKey: (value: V) => K | undefined): Map<K, V>;
/** @internal */
export function arrayToMap<K, V1, V2>(array: readonly V1[], makeKey: (value: V1) => K | undefined, makeValue: (value: V1) => V2): ESMap<K, V2>;
export function arrayToMap<K, V1, V2>(array: readonly V1[], makeKey: (value: V1) => K | undefined, makeValue: (value: V1) => V2): Map<K, V2>;
/** @internal */
export function arrayToMap<T>(array: readonly T[], makeKey: (value: T) => string | undefined): ESMap<string, T>;
export function arrayToMap<T>(array: readonly T[], makeKey: (value: T) => string | undefined): Map<string, T>;
/** @internal */
export function arrayToMap<T, U>(array: readonly T[], makeKey: (value: T) => string | undefined, makeValue: (value: T) => U): ESMap<string, U>;
export function arrayToMap<T, U>(array: readonly T[], makeKey: (value: T) => string | undefined, makeValue: (value: T) => U): Map<string, U>;
/** @internal */
export function arrayToMap<K, V1, V2>(array: readonly V1[], makeKey: (value: V1) => K | undefined, makeValue: (value: V1) => V1 | V2 = identity): ESMap<K, V1 | V2> {
export function arrayToMap<K, V1, V2>(array: readonly V1[], makeKey: (value: V1) => K | undefined, makeValue: (value: V1) => V1 | V2 = identity): Map<K, V1 | V2> {
const result = new Map<K, V1 | V2>();
for (const value of array) {
const key = makeKey(value);
@@ -1675,7 +1675,7 @@ export function maybeBind<T, A extends any[], R>(obj: T, fn: ((this: T, ...args:
}
/** @internal */
export interface MultiMap<K, V> extends ESMap<K, V[]> {
export interface MultiMap<K, V> extends Map<K, V[]> {
/**
* Adds the value to an array of values associated with the key, and returns the array.
* Creates the array if it does not already exist.
@@ -1798,10 +1798,10 @@ export function createSet<TElement, THash = number>(getHashCode: (element: TElem
const multiMap = new Map<THash, TElement | TElement[]>();
let size = 0;
function getElementIterator(): Iterator<TElement> {
function getElementIterator(): IterableIterator<TElement> {
const valueIt = multiMap.values();
let arrayIt: Iterator<TElement> | undefined;
return {
const it: IterableIterator<TElement> = {
next: () => {
while (true) {
if (arrayIt) {
@@ -1822,8 +1822,12 @@ export function createSet<TElement, THash = number>(getHashCode: (element: TElem
arrayIt = arrayIterator(n.value);
}
}
},
[Symbol.iterator]: () => {
return it;
}
};
return it;
}
const set: Set<TElement> = {
@@ -1904,34 +1908,40 @@ export function createSet<TElement, THash = number>(getHashCode: (element: TElem
get size() {
return size;
},
forEach(action: (value: TElement, key: TElement) => void): void {
forEach(action: (value: TElement, key: TElement, set: Set<TElement>) => void): void {
for (const elements of arrayFrom(multiMap.values())) {
if (isArray(elements)) {
for (const element of elements) {
action(element, element);
action(element, element, set);
}
}
else {
const element = elements;
action(element, element);
action(element, element, set);
}
}
},
keys(): Iterator<TElement> {
keys(): IterableIterator<TElement> {
return getElementIterator();
},
values(): Iterator<TElement> {
values(): IterableIterator<TElement> {
return getElementIterator();
},
entries(): Iterator<[TElement, TElement]> {
entries(): IterableIterator<[TElement, TElement]> {
const it = getElementIterator();
return {
const it2: IterableIterator<[TElement, TElement]> = {
next: () => {
const n = it.next();
return n.done ? n : { value: [ n.value, n.value ] };
}
},
[Symbol.iterator]: () => it2,
};
return it2;
},
[Symbol.iterator]: () => {
return getElementIterator();
},
[Symbol.toStringTag]: multiMap[Symbol.toStringTag],
};
return set;
-100
View File
@@ -35,63 +35,6 @@ export interface Collection<K> extends ReadonlyCollection<K> {
delete(key: K): boolean;
clear(): void;
}
/** ES6 Map interface, only read methods included. */
export interface ReadonlyESMap<K, V> extends ReadonlyCollection<K> {
get(key: K): V | undefined;
values(): Iterator<V>;
entries(): Iterator<[K, V]>;
forEach(action: (value: V, key: K) => void): void;
}
/**
* ES6 Map interface, only read methods included.
*/
export interface ReadonlyMap<T> extends ReadonlyESMap<string, T> {
}
/** ES6 Map interface. */
export interface ESMap<K, V> extends ReadonlyESMap<K, V>, Collection<K> {
set(key: K, value: V): this;
}
/**
* ES6 Map interface.
*/
export interface Map<T> extends ESMap<string, T> {
}
/** @internal */
export interface MapConstructor {
// eslint-disable-next-line @typescript-eslint/prefer-function-type
new <K, V>(iterable?: readonly (readonly [K, V])[] | ReadonlyESMap<K, V>): ESMap<K, V>;
}
/** ES6 Set interface, only read methods included. */
export interface ReadonlySet<T> extends ReadonlyCollection<T> {
has(value: T): boolean;
values(): Iterator<T>;
entries(): Iterator<[T, T]>;
forEach(action: (value: T, key: T) => void): void;
}
/** ES6 Set interface. */
export interface Set<T> extends ReadonlySet<T>, Collection<T> {
add(value: T): this;
delete(value: T): boolean;
}
/** @internal */
export interface SetConstructor {
// eslint-disable-next-line @typescript-eslint/prefer-function-type
new <T>(iterable?: readonly T[] | ReadonlySet<T>): Set<T>;
}
/** ES6 Iterator type. */
export interface Iterator<T> {
next(): { value: T, done?: false } | { value: void, done: true };
}
/** Array that is only intended to be pushed to, never read. */
export interface Push<T> {
push(...values: T[]): void;
@@ -110,46 +53,3 @@ export const enum Comparison {
EqualTo = 0,
GreaterThan = 1
}
/** @internal */
namespace NativeCollections {
declare const self: any;
const globals = typeof globalThis !== "undefined" ? globalThis :
typeof global !== "undefined" ? global :
typeof self !== "undefined" ? self :
undefined;
/**
* Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
*/
export function tryGetNativeMap(): MapConstructor {
// Internet Explorer's Map doesn't support iteration, so don't use it.
const gMap = globals?.Map;
// eslint-disable-next-line local/no-in-operator
const constructor = typeof gMap !== "undefined" && "entries" in gMap.prototype && new gMap([[0, 0]]).size === 1 ? gMap : undefined;
if (!constructor) {
throw new Error("No compatible Map implementation found.");
}
return constructor;
}
/**
* Returns the native Set implementation if it is available and compatible (i.e. supports iteration).
*/
export function tryGetNativeSet(): SetConstructor {
// Internet Explorer's Set doesn't support iteration, so don't use it.
const gSet = globals?.Set;
// eslint-disable-next-line local/no-in-operator
const constructor = typeof gSet !== "undefined" && "entries" in gSet.prototype && new gSet([0]).size === 1 ? gSet : undefined;
if (!constructor) {
throw new Error("No compatible Set implementation found.");
}
return constructor;
}
}
/** @internal */
export const Map = NativeCollections.tryGetNativeMap();
/** @internal */
export const Set = NativeCollections.tryGetNativeSet();
+2 -2
View File
@@ -10,8 +10,8 @@ import {
isOptionalTypeNode, isParameter, isParenthesizedTypeNode, isParseTreeNode, isPrivateIdentifier, isRestTypeNode,
isSetAccessorDeclaration, isStringLiteral, isThisTypeNode, isTupleTypeNode, isTypeLiteralNode, isTypeOperatorNode,
isTypeParameterDeclaration, isTypePredicateNode, isTypeQueryNode, isTypeReferenceNode, isUnionTypeNode, LiteralType,
map, Map, MatchingKeys, ModifierFlags, Node, NodeArray, NodeFlags, nodeIsSynthesized, noop, objectAllocator,
ObjectFlags, ObjectType, RelationComparisonResult, Set, Signature, SignatureCheckMode,
map, MatchingKeys, ModifierFlags, Node, NodeArray, NodeFlags, nodeIsSynthesized, noop, objectAllocator,
ObjectFlags, ObjectType, RelationComparisonResult, Signature, SignatureCheckMode,
SignatureFlags, SnippetKind, SortedReadonlyArray, stableSort, Symbol, SymbolFlags, symbolName, SyntaxKind,
TransformFlags, Type, TypeFacts, TypeFlags, TypeMapKind, TypeMapper, unescapeLeadingUnderscores, VarianceFlags,
version, Version, zipWith,
+17 -17
View File
@@ -16,7 +16,7 @@ import {
ElementAccessExpression, emitDetachedComments, EmitFileNames, EmitFlags, EmitHint, EmitHost,
emitNewLineBeforeLeadingCommentOfPosition, EmitOnly, EmitResolver, EmitResult, EmitTextWriter, EmitTransformers,
emptyArray, ensurePathIsNonModuleName, ensureTrailingDirectorySeparator, EntityName, EnumDeclaration, EnumMember,
escapeJsxAttributeString, escapeLeadingUnderscores, escapeNonAsciiString, escapeString, ESMap, every,
escapeJsxAttributeString, escapeLeadingUnderscores, escapeNonAsciiString, escapeString, every,
ExportAssignment, ExportDeclaration, ExportSpecifier, Expression, ExpressionStatement, ExpressionWithTypeArguments,
Extension, ExternalModuleReference, factory, fileExtensionIs, fileExtensionIsOneOf, FileReference, filter,
findIndex, firstOrUndefined, forEach, forEachChild, forEachLeadingCommentRange, forEachTrailingCommentRange,
@@ -52,7 +52,7 @@ import {
JSDocTypeTag, JSDocVariadicType, JsxAttribute, JsxAttributes, JsxClosingElement, JsxClosingFragment, JsxElement,
JsxEmit, JsxExpression, JsxFragment, JsxOpeningElement, JsxOpeningFragment, JsxSelfClosingElement,
JsxSpreadAttribute, JsxTagNameExpression, JsxText, LabeledStatement, last, lastOrUndefined, LateBoundDeclaration,
length, ListFormat, LiteralExpression, LiteralLikeNode, LiteralTypeNode, makeIdentifierFromModuleName, Map,
length, ListFormat, LiteralExpression, LiteralLikeNode, LiteralTypeNode, makeIdentifierFromModuleName,
MappedTypeNode, maybeBind, memoize, MetaProperty, MethodDeclaration, MethodSignature, Modifier, ModifierLike,
ModuleBlock, ModuleDeclaration, ModuleKind, ModuleReference, NamedDeclaration, NamedExports, NamedImports,
NamedImportsOrExports, NamedTupleMember, NamespaceExport, NamespaceExportDeclaration, NamespaceImport,
@@ -65,7 +65,7 @@ import {
PropertyAssignment, PropertyDeclaration, PropertySignature, QualifiedName, rangeEndIsOnSameLineAsRangeStart,
rangeEndPositionsAreOnSameLine, rangeIsOnSingleLine, rangeStartPositionsAreOnSameLine, readJsonOrUndefined,
removeFileExtension, resolvePath, RestTypeNode, returnFalse, ReturnStatement, returnUndefined, SatisfiesExpression,
ScriptTarget, Set, setEachParent, setOriginalNode, setParent, setTextRange, setTextRangePosEnd,
ScriptTarget, setEachParent, setOriginalNode, setParent, setTextRange, setTextRangePosEnd,
setTextRangePosWidth, ShorthandPropertyAssignment, SignatureDeclaration, singleOrUndefined,
skipPartiallyEmittedExpressions, skipTrivia, SnippetElement, SnippetKind, some, SourceFile,
SourceFilePrologueDirective, SourceFilePrologueInfo, SourceMapEmitResult, SourceMapGenerator, SourceMapSource,
@@ -192,10 +192,10 @@ function getSourceMapFilePath(jsFilePath: string, options: CompilerOptions) {
/** @internal */
export function getOutputExtension(fileName: string, options: CompilerOptions): Extension {
return fileExtensionIs(fileName, Extension.Json) ? Extension.Json :
options.jsx === JsxEmit.Preserve && fileExtensionIsOneOf(fileName, [Extension.Jsx, Extension.Tsx]) ? Extension.Jsx :
fileExtensionIsOneOf(fileName, [Extension.Mts, Extension.Mjs]) ? Extension.Mjs :
fileExtensionIsOneOf(fileName, [Extension.Cts, Extension.Cjs]) ? Extension.Cjs :
Extension.Js;
options.jsx === JsxEmit.Preserve && fileExtensionIsOneOf(fileName, [Extension.Jsx, Extension.Tsx]) ? Extension.Jsx :
fileExtensionIsOneOf(fileName, [Extension.Mts, Extension.Mjs]) ? Extension.Mjs :
fileExtensionIsOneOf(fileName, [Extension.Cts, Extension.Cjs]) ? Extension.Cjs :
Extension.Js;
}
function getOutputPathWithoutChangingExt(inputFileName: string, configFile: ParsedCommandLine, ignoreCase: boolean, outputDir: string | undefined, getCommonSourceDirectory?: () => string) {
@@ -992,8 +992,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
let nodeIdToGeneratedName: string[]; // Map of generated names for specific nodes.
let autoGeneratedIdToGeneratedName: string[]; // Map of generated names for temp and loop variables.
let generatedNames: Set<string>; // Set of names generated by the NameGenerator.
let formattedNameTempFlagsStack: (ESMap<string, TempFlags> | undefined)[];
let formattedNameTempFlags: ESMap<string, TempFlags> | undefined;
let formattedNameTempFlagsStack: (Map<string, TempFlags> | undefined)[];
let formattedNameTempFlags: Map<string, TempFlags> | undefined;
let privateNameTempFlagsStack: TempFlags[]; // Stack of enclosing name generation scopes.
let privateNameTempFlags: TempFlags; // TempFlags for the current name generation scope.
let tempFlagsStack: TempFlags[]; // Stack of enclosing name generation scopes.
@@ -1363,7 +1363,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
if (onEmitNode !== noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
return pipelineEmitWithNotification;
}
// falls through
// falls through
case PipelinePhase.Substitution:
if (substituteNode !== noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) {
if (currentParenthesizerRule) {
@@ -1371,17 +1371,17 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
}
return pipelineEmitWithSubstitution;
}
// falls through
// falls through
case PipelinePhase.Comments:
if (shouldEmitComments(node)) {
return pipelineEmitWithComments;
}
// falls through
// falls through
case PipelinePhase.SourceMaps:
if (shouldEmitSourceMaps(node)) {
return pipelineEmitWithSourceMaps;
}
// falls through
// falls through
case PipelinePhase.Emit:
return pipelineEmitWithHint;
default:
@@ -5081,7 +5081,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode);
return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` :
neverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? `"${escapeString(text)}"` :
`"${escapeNonAsciiString(text)}"`;
`"${escapeNonAsciiString(text)}"`;
}
else {
return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
@@ -5509,7 +5509,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
*/
function makeName(name: GeneratedIdentifier | GeneratedPrivateIdentifier) {
const prefix = formatGeneratedNamePart(name.autoGeneratePrefix, generateName);
const suffix = formatGeneratedNamePart (name.autoGenerateSuffix);
const suffix = formatGeneratedNamePart(name.autoGenerateSuffix);
switch (name.autoGenerateFlags & GeneratedIdentifierFlags.KindMask) {
case GeneratedIdentifierFlags.Auto:
return makeTempVariableName(TempFlags.Auto, !!(name.autoGenerateFlags & GeneratedIdentifierFlags.ReservedInNestedScopes), isPrivateIdentifier(name), prefix, suffix);
@@ -5829,7 +5829,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
}
function emitTrailingCommentOfPosition(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean) {
if(!currentSourceFile) return;
if (!currentSourceFile) return;
// trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
emitPos(commentPos);
@@ -6134,5 +6134,5 @@ function emitListItemWithParenthesizerRule(node: Node, emit: (node: Node, parent
function getEmitListItem<T extends Node, R extends ParenthesizerRuleOrSelector<T> | undefined>(emit: (node: Node, parenthesizerRule?: ((node: Node) => Node) | undefined) => void, parenthesizerRule: R): (node: Node, emit: (node: Node, parenthesizerRule?: ((node: Node) => Node) | undefined) => void, parenthesizerRule: R, index: number) => void {
return emit.length === 1 ? emitListItemNoParenthesizer :
typeof parenthesizerRule === "object" ? emitListItemWithParenthesizerRuleSelector :
emitListItemWithParenthesizerRule;
emitListItemWithParenthesizerRule;
}
+2 -2
View File
@@ -3,7 +3,7 @@ import {
createExpressionFromEntityName, Debug, EmitFlags, EmitHelper, EmitHelperUniqueNameCallback, EmitNode, EntityName,
Expression, FunctionExpression, GeneratedIdentifierFlags, getEmitFlags, getEmitScriptTarget,
getPropertyNameOfBindingOrAssignmentElement, Identifier, isCallExpression, isComputedPropertyName, isIdentifier,
memoize, PrivateIdentifierKind, ReadonlyESMap, ScriptTarget, setEmitFlags, setTextRange, SyntaxKind, TextRange,
memoize, PrivateIdentifierKind, ScriptTarget, setEmitFlags, setTextRange, SyntaxKind, TextRange,
TransformationContext, UnscopedEmitHelper,
} from "../_namespaces/ts";
@@ -1034,7 +1034,7 @@ export const classPrivateFieldInHelper: UnscopedEmitHelper = {
};`
};
let allUnscopedEmitHelpers: ReadonlyESMap<string, UnscopedEmitHelper> | undefined;
let allUnscopedEmitHelpers: ReadonlyMap<string, UnscopedEmitHelper> | undefined;
/** @internal */
export function getAllUnscopedEmitHelpers() {
+1 -1
View File
@@ -48,7 +48,7 @@ import {
JsxAttributeValue, JsxChild, JsxClosingElement, JsxClosingFragment, JsxElement, JsxExpression, JsxFragment,
JsxOpeningElement, JsxOpeningFragment, JsxSelfClosingElement, JsxSpreadAttribute, JsxTagNameExpression, JsxText,
KeywordSyntaxKind, KeywordToken, KeywordTypeNode, KeywordTypeSyntaxKind, LabeledStatement, LanguageVariant,
lastOrUndefined, LeftHandSideExpression, LiteralToken, LiteralTypeNode, map, Map, MappedTypeNode,
lastOrUndefined, LeftHandSideExpression, LiteralToken, LiteralTypeNode, map, MappedTypeNode,
memoize, memoizeOne, MergeDeclarationMarker, MetaProperty, MethodDeclaration, MethodSignature, MinusToken,
MissingDeclaration, Modifier, ModifierFlags, ModifierLike, modifiersToFlags, ModifierSyntaxKind, ModifierToken,
ModuleBlock, ModuleBody, ModuleDeclaration, ModuleKind, ModuleName, ModuleReference, Mutable, MutableNodeArray,
+4 -4
View File
@@ -1,11 +1,11 @@
import {
Associativity, BinaryExpression, BinaryOperator, cast, compareValues, Comparison, ConciseBody, ESMap, Expression,
Associativity, BinaryExpression, BinaryOperator, cast, compareValues, Comparison, ConciseBody, Expression,
getExpressionAssociativity, getExpressionPrecedence, getLeftmostExpression, getOperatorAssociativity,
getOperatorPrecedence, identity, isBinaryExpression, isBlock, isCallExpression, isCommaSequence,
isConditionalTypeNode, isConstructorTypeNode, isFunctionOrConstructorTypeNode, isFunctionTypeNode, isInferTypeNode,
isIntersectionTypeNode, isJSDocNullableType, isLeftHandSideExpression, isLiteralKind, isNamedTupleMember,
isNodeArray, isOptionalChain, isTypeOperatorNode, isUnaryExpression, isUnionTypeNode, last, LeftHandSideExpression,
Map, NamedTupleMember, NewExpression, NodeArray, NodeFactory, OperatorPrecedence, OuterExpressionKinds,
NamedTupleMember, NewExpression, NodeArray, NodeFactory, OperatorPrecedence, OuterExpressionKinds,
ParenthesizerRules, sameMap, setTextRange, skipPartiallyEmittedExpressions, some, SyntaxKind, TypeNode,
UnaryExpression,
} from "../_namespaces/ts";
@@ -16,8 +16,8 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul
cachedLiteralKind: SyntaxKind;
}
let binaryLeftOperandParenthesizerCache: ESMap<BinaryOperator, (node: Expression) => Expression> | undefined;
let binaryRightOperandParenthesizerCache: ESMap<BinaryOperator, (node: Expression) => Expression> | undefined;
let binaryLeftOperandParenthesizerCache: Map<BinaryOperator, (node: Expression) => Expression> | undefined;
let binaryRightOperandParenthesizerCache: Map<BinaryOperator, (node: Expression) => Expression> | undefined;
return {
getParenthesizeLeftSideOfBinaryForOperator,
+21 -21
View File
@@ -2,14 +2,14 @@ import {
append, appendIfUnique, arrayFrom, changeAnyExtension, CharacterCodes, combinePaths, comparePaths, Comparison,
CompilerOptions, contains, containsPath, createCompilerDiagnostic, Debug, Diagnostic, DiagnosticMessage,
DiagnosticReporter, Diagnostics, directoryProbablyExists, directorySeparator, emptyArray, endsWith,
ensureTrailingDirectorySeparator, ESMap, every, Extension, extensionIsTS, fileExtensionIs, fileExtensionIsOneOf,
ensureTrailingDirectorySeparator, every, Extension, extensionIsTS, fileExtensionIs, fileExtensionIsOneOf,
FileReference, filter, firstDefined, forEach, forEachAncestorDirectory, formatMessage, getBaseFileName,
GetCanonicalFileName, getCommonSourceDirectory, getDirectoryPath, GetEffectiveTypeRootsHost, getEmitModuleKind,
getEmitModuleResolutionKind, getModeForUsageLocation, getNormalizedAbsolutePath, getOwnKeys, getPathComponents,
getPathFromPathComponents, getPathsBasePath, getPossibleOriginalInputExtensionForExtension,
getRelativePathFromDirectory, getRootLength, hasJSFileExtension, hasProperty, hasTrailingDirectorySeparator,
hostGetCanonicalFileName, isArray, isExternalModuleNameRelative, isRootedDiskPath, isString,
isStringLiteralLike, lastOrUndefined, length, Map, MapLike, matchedText, MatchingKeys, matchPatternOrExact,
isStringLiteralLike, lastOrUndefined, length, MapLike, matchedText, MatchingKeys, matchPatternOrExact,
ModuleKind, ModuleResolutionHost, ModuleResolutionKind, noop, noopPush, normalizePath, normalizeSlashes,
optionsHaveModuleResolutionChanges, PackageId, packageIdToString, ParsedCommandLine, Path, pathIsRelative, Pattern,
patternText, perfLogger, Push, readJson, removeExtension, removeFileExtension, removePrefix,
@@ -620,7 +620,7 @@ export interface PackageJsonInfoCache {
/** @internal */ getPackageJsonInfo(packageJsonPath: string): PackageJsonInfo | boolean | undefined;
/** @internal */ setPackageJsonInfo(packageJsonPath: string, info: PackageJsonInfo | boolean): void;
/** @internal */ entries(): [Path, PackageJsonInfo | boolean][];
/** @internal */ getInternalMap(): ESMap<Path, PackageJsonInfo | boolean> | undefined;
/** @internal */ getInternalMap(): Map<Path, PackageJsonInfo | boolean> | undefined;
clear(): void;
}
@@ -631,18 +631,18 @@ export interface PerModuleNameCache {
/** @internal */
export interface CacheWithRedirects<T> {
getOwnMap: () => ESMap<string, T>;
redirectsMap: ESMap<Path, ESMap<string, T>>;
getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): ESMap<string, T>;
getOwnMap: () => Map<string, T>;
redirectsMap: Map<Path, Map<string, T>>;
getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): Map<string, T>;
clear(): void;
setOwnOptions(newOptions: CompilerOptions): void;
setOwnMap(newOwnMap: ESMap<string, T>): void;
setOwnMap(newOwnMap: Map<string, T>): void;
}
/** @internal */
export function createCacheWithRedirects<T>(options?: CompilerOptions): CacheWithRedirects<T> {
let ownMap: ESMap<string, T> = new Map();
const redirectsMap = new Map<Path, ESMap<string, T>>();
let ownMap: Map<string, T> = new Map();
const redirectsMap = new Map<Path, Map<string, T>>();
return {
getOwnMap,
redirectsMap,
@@ -660,7 +660,7 @@ export function createCacheWithRedirects<T>(options?: CompilerOptions): CacheWit
options = newOptions;
}
function setOwnMap(newOwnMap: ESMap<string, T>) {
function setOwnMap(newOwnMap: Map<string, T>) {
ownMap = newOwnMap;
}
@@ -685,7 +685,7 @@ export function createCacheWithRedirects<T>(options?: CompilerOptions): CacheWit
}
function createPackageJsonInfoCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): PackageJsonInfoCache {
let cache: ESMap<Path, PackageJsonInfo | boolean> | undefined;
let cache: Map<Path, PackageJsonInfo | boolean> | undefined;
return { getPackageJsonInfo, setPackageJsonInfo, clear, entries, getInternalMap };
function getPackageJsonInfo(packageJsonPath: string) {
return cache?.get(toPath(packageJsonPath, currentDirectory, getCanonicalFileName));
@@ -1321,8 +1321,8 @@ export enum NodeResolutionFeatures {
}
function node16ModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions,
host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference,
resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations {
host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference,
resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations {
return nodeNextModuleNameResolverWorker(
NodeResolutionFeatures.Node16Default,
moduleName,
@@ -1336,8 +1336,8 @@ function node16ModuleNameResolver(moduleName: string, containingFile: string, co
}
function nodeNextModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions,
host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference,
resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations {
host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference,
resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations {
return nodeNextModuleNameResolverWorker(
NodeResolutionFeatures.NodeNextDefault,
moduleName,
@@ -1874,7 +1874,7 @@ export interface PackageJsonInfoContents {
*
* @internal
*/
export function getPackageScopeForPath(fileName: string, state: ModuleResolutionState): PackageJsonInfo | undefined {
export function getPackageScopeForPath(fileName: string, state: ModuleResolutionState): PackageJsonInfo | undefined {
const parts = getPathComponents(fileName);
parts.pop();
while (parts.length > 0) {
@@ -2145,24 +2145,24 @@ function loadModuleFromImportsOrExports(extensions: Extensions, state: ModuleRes
const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports);
if (!endsWith(moduleName, directorySeparator) && moduleName.indexOf("*") === -1 && hasProperty(lookupTable, moduleName)) {
const target = (lookupTable as {[idx: string]: unknown})[moduleName];
const target = (lookupTable as { [idx: string]: unknown })[moduleName];
return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName);
}
const expandingKeys = sort(filter(getOwnKeys(lookupTable as MapLike<unknown>), k => k.indexOf("*") !== -1 || endsWith(k, "/")), comparePatternKeys);
for (const potentialTarget of expandingKeys) {
if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) {
const target = (lookupTable as {[idx: string]: unknown})[potentialTarget];
const target = (lookupTable as { [idx: string]: unknown })[potentialTarget];
const starPos = potentialTarget.indexOf("*");
const subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos));
return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget);
}
else if (endsWith(potentialTarget, "*") && startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) {
const target = (lookupTable as {[idx: string]: unknown})[potentialTarget];
const target = (lookupTable as { [idx: string]: unknown })[potentialTarget];
const subpath = moduleName.substring(potentialTarget.length - 1);
return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget);
}
else if (startsWith(moduleName, potentialTarget)) {
const target = (lookupTable as {[idx: string]: unknown})[potentialTarget];
const target = (lookupTable as { [idx: string]: unknown })[potentialTarget];
const subpath = moduleName.substring(potentialTarget.length);
return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false, potentialTarget);
}
@@ -2290,7 +2290,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
function useCaseSensitiveFileNames() {
return !state.host.useCaseSensitiveFileNames ? true :
typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames :
state.host.useCaseSensitiveFileNames();
state.host.useCaseSensitiveFileNames();
}
function tryLoadInputFileForPath(finalPath: string, entry: string, packagePath: string, isImports: boolean) {
+8 -8
View File
@@ -11,7 +11,7 @@ import {
getTextOfIdentifierOrLiteral, hasJSFileExtension, hasTSFileExtension, hostGetCanonicalFileName, Identifier,
isAmbientModule, isApplicableVersionedTypesKey, isExternalModuleAugmentation, isExternalModuleNameRelative,
isModuleBlock, isModuleDeclaration, isNonGlobalAmbientModule, isRootedDiskPath, isSourceFile, isString, JsxEmit,
map, Map, mapDefined, MapLike, matchPatternOrExact, min, ModuleDeclaration, ModuleKind, ModulePath,
map, mapDefined, MapLike, matchPatternOrExact, min, ModuleDeclaration, ModuleKind, ModulePath,
ModuleResolutionHost, ModuleResolutionKind, ModuleSpecifierCache, ModuleSpecifierOptions,
ModuleSpecifierResolutionHost, NodeFlags, NodeModulePathParts, normalizePath, Path, pathContainsNodeModules,
pathIsBareSpecifier, pathIsRelative, PropertyAccessExpression, removeFileExtension, removeSuffix, resolvePath,
@@ -35,9 +35,9 @@ function getPreferences(host: ModuleSpecifierResolutionHost, { importModuleSpeci
return {
relativePreference:
importModuleSpecifierPreference === "relative" ? RelativePreference.Relative :
importModuleSpecifierPreference === "non-relative" ? RelativePreference.NonRelative :
importModuleSpecifierPreference === "project-relative" ? RelativePreference.ExternalNonRelative :
RelativePreference.Shortest,
importModuleSpecifierPreference === "non-relative" ? RelativePreference.NonRelative :
importModuleSpecifierPreference === "project-relative" ? RelativePreference.ExternalNonRelative :
RelativePreference.Shortest,
ending: getEnding(),
};
function getEnding(): Ending {
@@ -62,7 +62,7 @@ function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpec
function isFormatRequiringExtensions(compilerOptions: CompilerOptions, importingSourceFileName: Path, host: ModuleSpecifierResolutionHost) {
if (getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Node16
&& getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeNext) {
&& getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeNext) {
return false;
}
return getImpliedNodeFormatForFile(importingSourceFileName, host.getPackageJsonInfoCache?.(), getModuleResolutionHost(host), compilerOptions) !== ModuleKind.CommonJS;
@@ -307,7 +307,7 @@ function computeModuleSpecifiers(
return pathsSpecifiers?.length ? pathsSpecifiers :
nodeModulesSpecifiers?.length ? nodeModulesSpecifiers :
Debug.checkDefined(relativeSpecifiers);
Debug.checkDefined(relativeSpecifiers);
}
interface Info {
@@ -736,7 +736,7 @@ function tryGetModuleNameFromExports(options: CompilerOptions, targetFilePath: s
const subPackageName = getNormalizedAbsolutePath(combinePaths(packageName, k), /*currentDirectory*/ undefined);
const mode = endsWith(k, "/") ? MatchingMode.Directory
: stringContains(k, "*") ? MatchingMode.Pattern
: MatchingMode.Exact;
: MatchingMode.Exact;
return tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, subPackageName, (exports as MapLike<unknown>)[k], conditions, mode);
});
}
@@ -776,7 +776,7 @@ function tryGetModuleNameFromRootDirs(rootDirs: readonly string[], moduleFileNam
: removeFileExtension(shortest);
}
function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCanonicalFileName, sourceDirectory }: Info, importingSourceFile: SourceFile , host: ModuleSpecifierResolutionHost, options: CompilerOptions, userPreferences: UserPreferences, packageNameOnly?: boolean, overrideMode?: ModuleKind.ESNext | ModuleKind.CommonJS): string | undefined {
function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCanonicalFileName, sourceDirectory }: Info, importingSourceFile: SourceFile, host: ModuleSpecifierResolutionHost, options: CompilerOptions, userPreferences: UserPreferences, packageNameOnly?: boolean, overrideMode?: ModuleKind.ESNext | ModuleKind.CommonJS): string | undefined {
if (!host.fileExists || !host.readFile) {
return undefined;
}
+5 -5
View File
@@ -12,7 +12,7 @@ import {
createDetachedDiagnostic, createNodeFactory, createScanner, createTextChangeRange, createTextSpanFromBounds, Debug,
Decorator, DefaultClause, DeleteExpression, Diagnostic, DiagnosticMessage, Diagnostics,
DiagnosticWithDetachedLocation, DoStatement, DotDotDotToken, ElementAccessExpression, emptyArray, emptyMap,
EndOfFileToken, ensureScriptKind, EntityName, EnumDeclaration, EnumMember, ESMap, ExclamationToken,
EndOfFileToken, ensureScriptKind, EntityName, EnumDeclaration, EnumMember, ExclamationToken,
ExportAssignment, ExportDeclaration, ExportSpecifier, Expression, ExpressionStatement, ExpressionWithTypeArguments,
ExternalModuleReference, fileExtensionIsOneOf, FileReference, findIndex, forEach, ForEachChildNodes,
ForInOrOfStatement, ForInStatement, ForOfStatement, ForStatement, FunctionDeclaration, FunctionExpression,
@@ -39,7 +39,7 @@ import {
JsxExpression, JsxFragment, JsxOpeningElement, JsxOpeningFragment, JsxOpeningLikeElement, JsxSelfClosingElement,
JsxSpreadAttribute, JsxTagNameExpression, JsxTagNamePropertyAccess, JsxText, JsxTokenSyntaxKind, LabeledStatement,
LanguageVariant, lastOrUndefined, LeftHandSideExpression, LiteralExpression, LiteralLikeNode, LiteralTypeNode, map,
Map, mapDefined, MappedTypeNode, MemberExpression, MetaProperty, MethodDeclaration, MethodSignature, MinusToken,
mapDefined, MappedTypeNode, MemberExpression, MetaProperty, MethodDeclaration, MethodSignature, MinusToken,
MissingDeclaration, Modifier, ModifierFlags, ModifierLike, ModifiersArray, modifiersToFlags, ModuleBlock,
ModuleDeclaration, ModuleKind, Mutable, NamedExportBindings, NamedExports, NamedImports, NamedImportsOrExports,
NamedTupleMember, NamespaceDeclaration, NamespaceExport, NamespaceExportDeclaration, NamespaceImport, NewExpression,
@@ -52,7 +52,7 @@ import {
PrivateIdentifier, PropertyAccessEntityNameExpression, PropertyAccessExpression, PropertyAssignment,
PropertyDeclaration, PropertyName, PropertySignature, QualifiedName, QuestionDotToken, QuestionToken,
ReadonlyKeyword, ReadonlyPragmaMap, ReadonlyTextRange, RestTypeNode, ReturnStatement, SatisfiesExpression,
ScriptKind, ScriptTarget, Set, SetAccessorDeclaration, setParent, setParentRecursive, setTextRange, setTextRangePos,
ScriptKind, ScriptTarget, SetAccessorDeclaration, setParent, setParentRecursive, setTextRange, setTextRangePos,
setTextRangePosEnd, setTextRangePosWidth, ShorthandPropertyAssignment, skipTrivia, some, SourceFile,
SpreadAssignment, SpreadElement, startsWith, Statement, StringLiteral, supportedDeclarationExtensions,
SwitchStatement, SyntaxKind, TaggedTemplateExpression, TemplateExpression, TemplateHead, TemplateLiteralToken,
@@ -1132,8 +1132,8 @@ namespace Parser {
let currentToken: SyntaxKind;
let nodeCount: number;
let identifiers: ESMap<string, string>;
let privateIdentifiers: ESMap<string, string>;
let identifiers: Map<string, string>;
let privateIdentifiers: Map<string, string>;
let identifierCount: number;
let parsingContext: ParsingContext;
+1 -1
View File
@@ -1,5 +1,5 @@
import {
Debug, Map, noop, Performance, PerformanceHooks, sys, System, timestamp, tryGetNativePerformanceHooks,
Debug, noop, Performance, PerformanceHooks, sys, System, timestamp, tryGetNativePerformanceHooks,
} from "./_namespaces/ts";
/** Performance measurements for the compiler. */
+14 -14
View File
@@ -14,7 +14,7 @@ import {
diagnosticCategoryName, DiagnosticMessage, DiagnosticMessageChain, DiagnosticReporter, Diagnostics,
DiagnosticWithLocation, directorySeparator, DirectoryStructureHost, emitFiles, EmitFlags, EmitHost, EmitOnly,
EmitResult, emptyArray, ensureTrailingDirectorySeparator, equateStringsCaseInsensitive, equateStringsCaseSensitive,
ESMap, explainIfFileIsRedirectAndImpliedFormat, ExportAssignment, ExportDeclaration, Extension, extensionFromPath,
explainIfFileIsRedirectAndImpliedFormat, ExportAssignment, ExportDeclaration, Extension, extensionFromPath,
externalHelpersModuleNameText, factory, fileExtensionIs, fileExtensionIsOneOf, FileIncludeKind, FileIncludeReason,
fileIncludeReasonToDiagnostics, FilePreprocessingDiagnostics, FilePreprocessingDiagnosticsKind, FileReference,
filter, find, firstDefined, firstDefinedIterator, flatMap, flatten, forEach, forEachAncestorDirectory, forEachChild,
@@ -39,7 +39,7 @@ import {
isImportDeclaration, isImportEqualsDeclaration, isImportSpecifier, isImportTypeNode, isIncrementalCompilation,
isInJSFile, isLiteralImportTypeNode, isModifier, isModuleDeclaration, isObjectLiteralExpression, isPlainJsFile,
isRequireCall, isRootedDiskPath, isSourceFileJS, isString, isStringLiteral, isStringLiteralLike, isTraceEnabled,
JsonSourceFile, JsxEmit, length, libMap, libs, Map, mapDefined, mapDefinedIterator, maybeBind, memoize,
JsonSourceFile, JsxEmit, length, libMap, libs, mapDefined, mapDefinedIterator, maybeBind, memoize,
MethodDeclaration, ModifierFlags, ModifierLike, ModuleBlock, ModuleDeclaration, ModuleKind, ModuleResolutionCache,
ModuleResolutionHost, ModuleResolutionInfo, moduleResolutionIsEqualTo, ModuleResolutionKind, Mutable, Node,
NodeArray, NodeFlags, nodeModulesPathPart, NodeWithTypeArguments, noop, normalizePath, notImplementedResolver,
@@ -50,7 +50,7 @@ import {
PropertyDeclaration, ReferencedFile, removeFileExtension, removePrefix, removeSuffix, resolutionExtensionIsTSOrJson,
resolveConfigFileProjectName, ResolvedConfigFileName, ResolvedModuleFull, ResolvedModuleWithFailedLookupLocations,
ResolvedProjectReference, ResolvedTypeReferenceDirective, resolveModuleName, resolveModuleNameFromCache,
resolveTypeReferenceDirective, returnFalse, returnUndefined, SatisfiesExpression, ScriptKind, ScriptTarget, Set,
resolveTypeReferenceDirective, returnFalse, returnUndefined, SatisfiesExpression, ScriptKind, ScriptTarget,
setParent, setParentRecursive, setResolvedModule, setResolvedTypeReferenceDirective, skipTrivia, skipTypeChecking,
some, sortAndDeduplicateDiagnostics, SortedReadonlyArray, SourceFile, sourceFileAffectingCompilerOptions,
sourceFileMayBeEmitted, SourceOfProjectReferenceRedirect, stableSort, startsWith, Statement, stringContains,
@@ -253,7 +253,7 @@ export function changeCompilerHostLikeToUseCache(
const readFileCache = new Map<Path, string | false>();
const fileExistsCache = new Map<Path, boolean>();
const directoryExistsCache = new Map<Path, boolean>();
const sourceFileCache = new Map<SourceFile["impliedNodeFormat"], ESMap<Path, SourceFile>>();
const sourceFileCache = new Map<SourceFile["impliedNodeFormat"], Map<Path, SourceFile>>();
const readFileWithCache = (fileName: string): string | undefined => {
const key = toPath(fileName);
@@ -636,7 +636,7 @@ export function isExclusivelyTypeOnlyImportOrExport(decl: ImportDeclaration | Ex
* @param usage The module reference string
* @returns The final resolution mode of the import
*/
export function getModeForUsageLocation(file: {impliedNodeFormat?: SourceFile["impliedNodeFormat"]}, usage: StringLiteralLike) {
export function getModeForUsageLocation(file: { impliedNodeFormat?: SourceFile["impliedNodeFormat"] }, usage: StringLiteralLike) {
if (file.impliedNodeFormat === undefined) return undefined;
if ((isImportDeclaration(usage.parent) || isExportDeclaration(usage.parent))) {
const isTypeOnly = isExclusivelyTypeOnlyImportOrExport(usage.parent);
@@ -760,7 +760,7 @@ function forEachProjectReference<T>(
export const inferredTypesContainingFile = "__inferred type names__.ts";
interface DiagnosticCache<T extends Diagnostic> {
perFile?: ESMap<Path, readonly T[]>;
perFile?: Map<Path, readonly T[]>;
allDiagnostics?: readonly T[];
}
@@ -885,7 +885,7 @@ export function isProgramUptoDate(
function resolvedProjectReferenceUptoDate(oldResolvedRef: ResolvedProjectReference | undefined, oldRef: ProjectReference): boolean {
if (oldResolvedRef) {
// Assume true
// Assume true
if (contains(seenResolvedRefs, oldResolvedRef)) return true;
const refPath = resolveProjectReferencePath(oldRef);
@@ -948,8 +948,8 @@ export function getImpliedNodeFormatForFileWorker(
case ModuleResolutionKind.NodeNext:
return fileExtensionIsOneOf(fileName, [Extension.Dmts, Extension.Mts, Extension.Mjs]) ? ModuleKind.ESNext :
fileExtensionIsOneOf(fileName, [Extension.Dcts, Extension.Cts, Extension.Cjs]) ? ModuleKind.CommonJS :
fileExtensionIsOneOf(fileName, [Extension.Dts, Extension.Ts, Extension.Tsx, Extension.Js, Extension.Jsx]) ? lookupFromPackageJson() :
undefined; // other extensions, like `json` or `tsbuildinfo`, are set as `undefined` here but they should never be fed through the transformer pipeline
fileExtensionIsOneOf(fileName, [Extension.Dts, Extension.Ts, Extension.Tsx, Extension.Js, Extension.Jsx]) ? lookupFromPackageJson() :
undefined; // other extensions, like `json` or `tsbuildinfo`, are set as `undefined` here but they should never be fed through the transformer pipeline
default:
return undefined;
}
@@ -1250,9 +1250,9 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
// A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
let resolvedProjectReferences: readonly (ResolvedProjectReference | undefined)[] | undefined;
let projectReferenceRedirects: ESMap<Path, ResolvedProjectReference | false> | undefined;
let mapFromFileToProjectReferenceRedirects: ESMap<Path, Path> | undefined;
let mapFromToProjectReferenceRedirectSource: ESMap<Path, SourceOfProjectReferenceRedirect> | undefined;
let projectReferenceRedirects: Map<Path, ResolvedProjectReference | false> | undefined;
let mapFromFileToProjectReferenceRedirects: Map<Path, Path> | undefined;
let mapFromToProjectReferenceRedirectSource: Map<Path, SourceOfProjectReferenceRedirect> | undefined;
const useSourceOfProjectReferenceRedirect = !!host.useSourceOfProjectReferenceRedirect?.() &&
!options.disableSourceOfProjectReferenceRedirect;
@@ -2309,7 +2309,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
}
function getCachedSemanticDiagnostics(sourceFile?: SourceFile): readonly Diagnostic[] | undefined {
return sourceFile
return sourceFile
? cachedBindAndCheckDiagnosticsForFile.perFile?.get(sourceFile.path)
: cachedBindAndCheckDiagnosticsForFile.allDiagnostics;
}
@@ -2400,7 +2400,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
// - check JS: .js files with either // ts-check or checkJs: true
// - external: files that are added by plugins
const includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === ScriptKind.TS || sourceFile.scriptKind === ScriptKind.TSX
|| sourceFile.scriptKind === ScriptKind.External || isPlainJs || isCheckJs || sourceFile.scriptKind === ScriptKind.Deferred);
|| sourceFile.scriptKind === ScriptKind.External || isPlainJs || isCheckJs || sourceFile.scriptKind === ScriptKind.Deferred);
let bindDiagnostics: readonly Diagnostic[] = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray;
let checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : emptyArray;
if (isPlainJs) {
+11 -11
View File
@@ -3,18 +3,18 @@ import {
arrayToMap, CachedDirectoryStructureHost, CacheWithRedirects, CharacterCodes, clearMap, closeFileWatcher,
closeFileWatcherOf, CompilerOptions, contains, createCacheWithRedirects, createModeAwareCache,
createModuleResolutionCache, createMultiMap, createTypeReferenceDirectiveResolutionCache, Debug, Diagnostics,
directorySeparator, DirectoryWatcherCallback, emptyArray, emptyIterator, endsWith, ESMap, Extension, extensionIsTS,
directorySeparator, DirectoryWatcherCallback, emptyArray, emptyIterator, endsWith, Extension, extensionIsTS,
fileExtensionIs, fileExtensionIsOneOf, FileReference, FileWatcher, FileWatcherCallback, firstDefinedIterator,
GetCanonicalFileName, getDirectoryPath, getEffectiveTypeRoots, getModeForFileReference, getModeForResolutionAtIndex,
getModeForUsageLocation, getNormalizedAbsolutePath, getResolutionName, getRootLength, HasInvalidatedResolutions,
ignoredPaths, inferredTypesContainingFile, isEmittedFileOfProgram, isExternalModuleNameRelative,
isExternalOrCommonJsModule, isNodeModulesDirectory, isRootedDiskPath, isString, isStringLiteralLike, isTraceEnabled,
length, loadModuleFromGlobalCache, Map, memoize, MinimalResolutionCacheHost, ModeAwareCache, ModuleKind,
length, loadModuleFromGlobalCache, memoize, MinimalResolutionCacheHost, ModeAwareCache, ModuleKind,
ModuleResolutionCache, ModuleResolutionHost, ModuleResolutionInfo, mutateMap, noopFileWatcher, normalizePath,
PackageId, packageIdToString, parseNodeModuleFromPath, Path, pathContainsNodeModules, PerModuleNameCache, Program,
ReadonlyESMap, removeSuffix, removeTrailingDirectorySeparator, resolutionExtensionIsTSOrJson, ResolvedModuleFull,
removeSuffix, removeTrailingDirectorySeparator, resolutionExtensionIsTSOrJson, ResolvedModuleFull,
ResolvedModuleWithFailedLookupLocations, ResolvedProjectReference, ResolvedTypeReferenceDirective,
ResolvedTypeReferenceDirectiveWithFailedLookupLocations, returnTrue, Set, some, SourceFile, startsWith,
ResolvedTypeReferenceDirectiveWithFailedLookupLocations, returnTrue, some, SourceFile, startsWith,
stringContains, trace, TypeReferenceDirectiveResolutionInfo, unorderedRemoveItem, WatchDirectoryFlags,
} from "./_namespaces/ts";
@@ -48,7 +48,7 @@ export interface ResolutionCache {
invalidateResolutionOfFile(filePath: Path): void;
removeResolutionsOfFile(filePath: Path): void;
removeResolutionsFromProjectReferenceRedirects(filePath: Path): void;
setFilesWithInvalidatedNonRelativeUnresolvedImports(filesWithUnresolvedImports: ESMap<Path, readonly string[]>): void;
setFilesWithInvalidatedNonRelativeUnresolvedImports(filesWithUnresolvedImports: Map<Path, readonly string[]>): void;
createHasInvalidatedResolutions(customHasInvalidatedResolutions: HasInvalidatedResolutions): HasInvalidatedResolutions;
hasChangedAutomaticTypeDirectiveNames(): boolean;
isFileWithInvalidatedNonRelativeUnresolvedImports(path: Path): boolean;
@@ -201,7 +201,7 @@ type GetResolutionWithResolvedFileName<T extends ResolutionWithFailedLookupLocat
export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootDirForResolution: string | undefined, logChangesWhenResolvingModule: boolean): ResolutionCache {
let filesWithChangedSetOfUnresolvedImports: Path[] | undefined;
let filesWithInvalidatedResolutions: Set<Path> | undefined;
let filesWithInvalidatedNonRelativeUnresolvedImports: ReadonlyESMap<Path, readonly string[]> | undefined;
let filesWithInvalidatedNonRelativeUnresolvedImports: ReadonlyMap<Path, readonly string[]> | undefined;
const nonRelativeExternalModuleResolutions = createMultiMap<ResolutionWithFailedLookupLocations>();
const resolutionsWithFailedLookups: ResolutionWithFailedLookupLocations[] = [];
@@ -445,7 +445,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD
names: readonly string[] | readonly FileReference[];
containingFile: string;
redirectedReference: ResolvedProjectReference | undefined;
cache: ESMap<Path, ModeAwareCache<T>>;
cache: Map<Path, ModeAwareCache<T>>;
perDirectoryCacheWithRedirects: CacheWithRedirects<ModeAwareCache<T>>;
loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, containingSourceFile?: SourceFile, resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext | undefined) => T;
getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName<T, R>;
@@ -517,8 +517,8 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD
loader === resolveModuleName as unknown ?
resolved?.resolvedFileName ?
resolved.packagetId ?
Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4:
Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3:
Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4 :
Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3 :
Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved :
resolved?.resolvedFileName ?
resolved.packagetId ?
@@ -966,7 +966,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD
}
function removeResolutionsOfFileFromCache<T extends ResolutionWithFailedLookupLocations, R extends ResolutionWithResolvedFileName>(
cache: ESMap<string, ModeAwareCache<T>>,
cache: Map<string, ModeAwareCache<T>>,
filePath: Path,
getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName<T, R>,
) {
@@ -1023,7 +1023,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD
}
}
function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap: ReadonlyESMap<Path, readonly string[]>) {
function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap: ReadonlyMap<Path, readonly string[]>) {
Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
}
+3 -3
View File
@@ -1,7 +1,7 @@
import {
append, arraysEqual, binarySearch, CharacterCodes, CommentDirective, CommentDirectiveType, CommentKind,
CommentRange, compareValues, Debug, DiagnosticMessage, Diagnostics, ESMap, getEntries, identity, JSDocSyntaxKind,
JsxTokenSyntaxKind, KeywordSyntaxKind, LanguageVariant, LineAndCharacter, Map, MapLike, parsePseudoBigInt,
CommentRange, compareValues, Debug, DiagnosticMessage, Diagnostics, getEntries, identity, JSDocSyntaxKind,
JsxTokenSyntaxKind, KeywordSyntaxKind, LanguageVariant, LineAndCharacter, MapLike, parsePseudoBigInt,
positionIsSynthesized, ScriptTarget, SourceFileLike, SyntaxKind, TokenFlags, trimStringStart,
} from "./_namespaces/ts";
@@ -347,7 +347,7 @@ function isUnicodeIdentifierPart(code: number, languageVersion: ScriptTarget | u
lookupInUnicodeMap(code, unicodeES3IdentifierPart);
}
function makeReverseMap(source: ESMap<string, number>): string[] {
function makeReverseMap(source: Map<string, number>): string[] {
const result: string[] = [];
source.forEach((value, name) => {
result[value] = name;
+3 -3
View File
@@ -1,8 +1,8 @@
import {
arrayFrom, binarySearchKey, CharacterCodes, combinePaths, compareValues, Debug, DocumentPosition,
DocumentPositionMapper, DocumentPositionMapperHost, EmitHost, emptyArray, ESMap, every, getDirectoryPath,
DocumentPositionMapper, DocumentPositionMapperHost, EmitHost, emptyArray, every, getDirectoryPath,
getNormalizedAbsolutePath, getPositionOfLineAndCharacter, getRelativePathToDirectoryOrUrl, identity, isArray,
isString, Iterator, LineAndCharacter, Map, RawSourceMap, some, sortAndDeduplicate, SortedReadonlyArray,
isString, LineAndCharacter, RawSourceMap, some, sortAndDeduplicate, SortedReadonlyArray,
SourceMapGenerator, trimStringEnd,
} from "./_namespaces/ts";
import * as performance from "./_namespaces/ts.performance";
@@ -25,7 +25,7 @@ export function createSourceMapGenerator(host: EmitHost, file: string, sourceRoo
let sourcesContent: (string | null)[] | undefined;
const names: string[] = [];
let nameToNameIndexMap: ESMap<string, number> | undefined;
let nameToNameIndexMap: Map<string, number> | undefined;
const mappingCharCodes: number[] = [];
let mappings = "";
+4 -4
View File
@@ -1,9 +1,9 @@
import {
AssertionLevel, closeFileWatcher, closeFileWatcherOf, combinePaths, Comparison, contains, containsPath,
createGetCanonicalFileName, createMultiMap, Debug, directorySeparator, emptyArray, emptyFileSystemEntries, endsWith,
enumerateInsertsAndDeletes, ESMap, FileSystemEntries, getDirectoryPath, getFallbackOptions,
enumerateInsertsAndDeletes, FileSystemEntries, getDirectoryPath, getFallbackOptions,
getNormalizedAbsolutePath, getRelativePathToDirectoryOrUrl, getRootLength, getStringComparer, isArray, isNodeLikeSystem, isString,
Map, mapDefined, matchesExclude, matchFiles, memoize, noop, normalizePath, normalizeSlashes, orderedRemoveItem,
mapDefined, matchesExclude, matchFiles, memoize, noop, normalizePath, normalizeSlashes, orderedRemoveItem,
Path, perfLogger, PollingWatchKind, RequireResult, resolveJSModule, some, startsWith, stringContains, timestamp,
unorderedRemoveItem, WatchDirectoryKind, WatchFileKind, WatchOptions, writeFileEnsuringDirectories,
} from "./_namespaces/ts";
@@ -434,7 +434,7 @@ interface SingleFileWatcher<T extends FileWatcherCallback | FsWatchCallback>{
callbacks: T[];
}
function createSingleWatcherPerName<T extends FileWatcherCallback | FsWatchCallback>(
cache: Map<SingleFileWatcher<T>>,
cache: Map<string, SingleFileWatcher<T>>,
useCaseSensitiveFileNames: boolean,
name: string,
callback: T,
@@ -610,7 +610,7 @@ function createDirectoryWatcherSupportingRecursive({
};
}
type InvokeMap = ESMap<Path, string[] | true>;
type InvokeMap = Map<Path, string[] | true>;
function invokeCallbacks(dirPath: Path, fileName: string): void;
function invokeCallbacks(dirPath: Path, invokeMap: InvokeMap, fileNames: string[] | undefined): void;
function invokeCallbacks(dirPath: Path, fileNameOrInvokeMap: string | InvokeMap, fileNames?: string[]) {
+1 -1
View File
@@ -1,6 +1,6 @@
import {
combinePaths, ConditionalType, Debug, EvolvingArrayType, getLineAndCharacterOfPosition, getSourceFileOfNode,
IndexedAccessType, IndexType, IntersectionType, LineAndCharacter, Map, Node, ObjectFlags, Path, ReverseMappedType,
IndexedAccessType, IndexType, IntersectionType, LineAndCharacter, Node, ObjectFlags, Path, ReverseMappedType,
SubstitutionType, timestamp, Type, TypeFlags, TypeReference, unescapeLeadingUnderscores, UnionType,
} from "./_namespaces/ts";
import * as performance from "./_namespaces/ts.performance";
+3 -3
View File
@@ -5,7 +5,7 @@ import {
classOrConstructorParameterIsDecorated, ClassStaticBlockDeclaration, compact, ComputedPropertyName,
ConstructorDeclaration, createAccessorPropertyBackingField, createAccessorPropertyGetRedirector,
createAccessorPropertySetRedirector, createMemberAccessForPropertyName, Debug, ElementAccessExpression, EmitFlags,
EmitHint, ESMap, expandPreOrPostfixIncrementOrDecrementExpression, Expression, ExpressionStatement,
EmitHint, expandPreOrPostfixIncrementOrDecrementExpression, Expression, ExpressionStatement,
ExpressionWithTypeArguments, factory, filter, findSuperStatementIndex, ForStatement, GeneratedIdentifier,
GeneratedIdentifierFlags, GeneratedNamePart, GeneratedPrivateIdentifier, GetAccessorDeclaration, getCommentRange,
getEffectiveBaseTypeNode, getEmitFlags, getEmitScriptTarget, getInitializerOfBindingOrAssignmentElement,
@@ -24,7 +24,7 @@ import {
isPropertyAssignment, isPropertyDeclaration, isPropertyName, isSetAccessor, isSetAccessorDeclaration,
isShorthandPropertyAssignment, isSimpleCopiableExpression, isSimpleInlineableExpression, isSpreadAssignment,
isSpreadElement, isStatement, isStatic, isStaticModifier, isSuperProperty, isTemplateLiteral, isThisProperty,
LeftHandSideExpression, map, Map, MethodDeclaration, Modifier, ModifierFlags, moveRangePastModifiers, moveRangePos,
LeftHandSideExpression, map, MethodDeclaration, Modifier, ModifierFlags, moveRangePastModifiers, moveRangePos,
Node, NodeCheckFlags, nodeIsSynthesized, ObjectLiteralElementLike, PostfixUnaryExpression, PrefixUnaryExpression,
PrivateIdentifier, PrivateIdentifierPropertyAccessExpression, PrivateIdentifierPropertyDeclaration,
PropertyAccessExpression, PropertyDeclaration, PropertyName, ScriptTarget, SetAccessorDeclaration, setCommentRange,
@@ -135,7 +135,7 @@ interface PrivateIdentifierEnvironment {
/**
* A mapping of generated private names to information needed for transformation.
*/
generatedIdentifiers?: ESMap<Node, PrivateIdentifierInfo>;
generatedIdentifiers?: Map<Node, PrivateIdentifierInfo>;
}
interface ClassLexicalEnvironment {
+8 -8
View File
@@ -6,7 +6,7 @@ import {
createEmptyExports, createGetSymbolAccessibilityDiagnosticForNode,
createGetSymbolAccessibilityDiagnosticForNodeName, createSymbolTable, createUnparsedSourceFile, Debug, Declaration,
DeclarationDiagnosticProducing, DeclarationName, declarationNameToString, Diagnostics, DiagnosticWithLocation,
EmitFlags, EmitHost, EmitResolver, emptyArray, EntityNameOrEntityNameExpression, EnumDeclaration, ESMap,
EmitFlags, EmitHost, EmitResolver, emptyArray, EntityNameOrEntityNameExpression, EnumDeclaration,
ExportAssignment, ExportDeclaration, ExpressionWithTypeArguments, factory, FileReference, filter, flatMap, flatten,
forEach, FunctionDeclaration, FunctionTypeNode, GeneratedIdentifierFlags, GetAccessorDeclaration, getCommentRange,
getDirectoryPath, getEffectiveBaseTypeNode, getEffectiveModifierFlags,
@@ -27,11 +27,11 @@ import {
isSemicolonClassElement, isSetAccessorDeclaration, isSourceFile, isSourceFileJS, isSourceFileNotJson,
isStringANonContextualKeyword, isStringLiteral, isStringLiteralLike, isTupleTypeNode, isTypeAliasDeclaration,
isTypeNode, isTypeParameterDeclaration, isTypeQueryNode, isUnparsedSource, last, LateBoundDeclaration,
LateVisibilityPaintedStatement, length, map, Map, mapDefined, MethodDeclaration, MethodSignature, Modifier,
LateVisibilityPaintedStatement, length, map, mapDefined, MethodDeclaration, MethodSignature, Modifier,
ModifierFlags, ModuleBody, ModuleDeclaration, NamedDeclaration, NamespaceDeclaration,
needsScopeMarker, Node, NodeArray, NodeBuilderFlags, NodeFlags, NodeId, normalizeSlashes, OmittedExpression,
orderedRemoveItem, ParameterDeclaration, parseNodeFactory, pathContainsNodeModules, pathIsRelative,
PropertyDeclaration, PropertySignature, pushIfUnique, removeAllComments, Set, SetAccessorDeclaration,
PropertyDeclaration, PropertySignature, pushIfUnique, removeAllComments, SetAccessorDeclaration,
setCommentRange, setEmitFlags, setOriginalNode, setParent, setTextRange, SignatureDeclaration, skipTrivia, some,
SourceFile, startsWith, Statement, stringContains, StringLiteral, Symbol, SymbolAccessibility,
SymbolAccessibilityResult, SymbolFlags, SymbolTracker, SyntaxKind, toFileNameLowerCase, toPath,
@@ -105,7 +105,7 @@ export function transformDeclarations(context: TransformationContext) {
let enclosingDeclaration: Node;
let necessaryTypeReferences: Set<[specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined]> | undefined;
let lateMarkedStatements: LateVisibilityPaintedStatement[] | undefined;
let lateStatementReplacementMap: ESMap<NodeId, VisitResult<LateVisibilityPaintedStatement | ExportAssignment>>;
let lateStatementReplacementMap: Map<NodeId, VisitResult<LateVisibilityPaintedStatement | ExportAssignment>>;
let suppressNewDiagnosticContexts: boolean;
let exportedModulesFromDeclarationEmit: Symbol[] | undefined;
@@ -130,8 +130,8 @@ export function transformDeclarations(context: TransformationContext) {
let errorFallbackNode: Declaration | undefined;
let currentSourceFile: SourceFile;
let refs: ESMap<NodeId, SourceFile>;
let libs: ESMap<string, boolean>;
let refs: Map<NodeId, SourceFile>;
let libs: Map<string, boolean>;
let emittedImports: readonly AnyImportSyntax[] | undefined; // must be declared in container so it can be `undefined` while transformer's first pass
const resolver = context.getEmitResolver();
const options = context.getCompilerOptions();
@@ -477,7 +477,7 @@ export function transformDeclarations(context: TransformationContext) {
}
}
function collectReferences(sourceFile: SourceFile | UnparsedSource, ret: ESMap<NodeId, SourceFile>) {
function collectReferences(sourceFile: SourceFile | UnparsedSource, ret: Map<NodeId, SourceFile>) {
if (noResolve || (!isUnparsedSource(sourceFile) && isSourceFileJS(sourceFile))) return ret;
forEach(sourceFile.referencedFiles, f => {
const elem = host.getSourceFileFromReference(sourceFile, f);
@@ -488,7 +488,7 @@ export function transformDeclarations(context: TransformationContext) {
return ret;
}
function collectLibs(sourceFile: SourceFile | UnparsedSource, ret: ESMap<string, boolean>) {
function collectLibs(sourceFile: SourceFile | UnparsedSource, ret: Map<string, boolean>) {
forEach(sourceFile.libReferenceDirectives, ref => {
const lib = host.getLibFileFromReference(ref);
if (lib) {
+6 -6
View File
@@ -4,7 +4,7 @@ import {
Block, BreakOrContinueStatement, CallExpression, CaseBlock, CaseClause, cast, CatchClause, chainBundle,
ClassDeclaration, ClassElement, ClassExpression, ClassLikeDeclaration, CommaListExpression, ComputedPropertyName,
concatenate, ConstructorDeclaration, createExpressionForPropertyName, createMemberAccessForPropertyName,
createRange, createTokenRange, Debug, Declaration, DoStatement, elementAt, EmitFlags, EmitHint, emptyArray, ESMap,
createRange, createTokenRange, Debug, Declaration, DoStatement, elementAt, EmitFlags, EmitHint, emptyArray,
Expression, ExpressionStatement, ExpressionWithTypeArguments, filter, first, firstOrUndefined, flatMap, flatten,
flattenDestructuringAssignment, flattenDestructuringBinding, FlattenLevel, ForInStatement, ForOfStatement,
ForStatement, FunctionBody, FunctionDeclaration, FunctionExpression, FunctionLikeDeclaration,
@@ -22,7 +22,7 @@ import {
isPrologueDirective, isPropertyDeclaration, isPropertyName, isReturnStatement, isSpreadElement, isStatement,
isStatic, isSuperProperty, isSwitchStatement, isTryStatement, isVariableDeclarationList, isVariableStatement,
isWithStatement, IterationStatement, LabeledStatement, last, lastOrUndefined, LeftHandSideExpression,
LiteralExpression, map, Map, MetaProperty, MethodDeclaration, ModifierFlags, moveRangeEnd, moveRangePos,
LiteralExpression, map, MetaProperty, MethodDeclaration, ModifierFlags, moveRangeEnd, moveRangePos,
moveSyntheticComments, NamedDeclaration, NewExpression, Node, NodeArray, NodeCheckFlags, NodeFlags,
nodeIsSynthesized, NumericLiteral, ObjectLiteralElementLike, ObjectLiteralExpression, ParameterDeclaration,
ParenthesizedExpression, PrimaryExpression, ProcessLevel, processTaggedTemplateExpression, PropertyAssignment,
@@ -108,15 +108,15 @@ interface ConvertedLoopState {
* set of labels that occurred inside the converted loop
* used to determine if labeled jump can be emitted as is or it should be dispatched to calling code
*/
labels?: ESMap<string, boolean>;
labels?: Map<string, boolean>;
/*
* collection of labeled jumps that transfer control outside the converted loop.
* maps store association 'label -> labelMarker' where
* - label - value of label as it appear in code
* - label marker - return value that should be interpreted by calling code as 'jump to <label>'
*/
labeledNonLocalBreaks?: ESMap<string, string>;
labeledNonLocalContinues?: ESMap<string, string>;
labeledNonLocalBreaks?: Map<string, string>;
labeledNonLocalContinues?: Map<string, string>;
/*
* set of non-labeled jumps that transfer control outside the converted loop
@@ -3453,7 +3453,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile
}
}
function processLabeledJumps(table: ESMap<string, string>, isBreak: boolean, loopResultName: Identifier, outerLoop: ConvertedLoopState | undefined, caseClauses: CaseClause[]): void {
function processLabeledJumps(table: Map<string, string>, isBreak: boolean, loopResultName: Identifier, outerLoop: ConvertedLoopState | undefined, caseClauses: CaseClause[]): void {
if (!table) {
return;
}
+3 -3
View File
@@ -10,7 +10,7 @@ import {
isFunctionLikeDeclaration, isIdentifier, isModifierLike, isNodeWithPossibleHoistedDeclaration, isOmittedExpression,
isPropertyAccessExpression, isStatement, isSuperProperty, isToken, isVariableDeclarationList,
LeftHandSideExpression, map, MethodDeclaration, Node, NodeCheckFlags, NodeFactory, NodeFlags, ParameterDeclaration,
PropertyAccessExpression, PropertyAssignment, ScriptTarget, Set, SetAccessorDeclaration, setEmitFlags,
PropertyAccessExpression, PropertyAssignment, ScriptTarget, SetAccessorDeclaration, setEmitFlags,
setOriginalNode, setSourceMapRange, setTextRange, some, SourceFile, Statement, SyntaxKind, TextRange,
TransformationContext, TransformFlags, TypeNode, TypeReferenceSerializationKind, unescapeLeadingUnderscores,
VariableDeclaration, VariableDeclarationList, VariableStatement, visitEachChild, visitFunctionBody,
@@ -837,7 +837,7 @@ export function createSuperAccessVariableStatement(factory: NodeFactory, resolve
factory.createArrowFunction(
/* modifiers */ undefined,
/* typeParameters */ undefined,
/* parameters */ [],
/* parameters */[],
/* type */ undefined,
/* equalsGreaterThanToken */ undefined,
setEmitFlags(
@@ -859,7 +859,7 @@ export function createSuperAccessVariableStatement(factory: NodeFactory, resolve
factory.createArrowFunction(
/* modifiers */ undefined,
/* typeParameters */ undefined,
/* parameters */ [
/* parameters */[
factory.createParameterDeclaration(
/* modifiers */ undefined,
/* dotDotDotToken */ undefined,
+41 -41
View File
@@ -12,7 +12,7 @@ import {
isPropertyAccessExpression, isPropertyName, isStatement, isSuperProperty, isToken, isVariableDeclarationList,
LabeledStatement, LeftHandSideExpression, MethodDeclaration, ModifierFlags, Node, NodeCheckFlags, NodeFlags,
ObjectLiteralElementLike, ObjectLiteralExpression, ParameterDeclaration, ParenthesizedExpression, ProcessLevel,
processTaggedTemplateExpression, PropertyAccessExpression, ReturnStatement, ScriptTarget, Set,
processTaggedTemplateExpression, PropertyAccessExpression, ReturnStatement, ScriptTarget,
SetAccessorDeclaration, setEmitFlags, setOriginalNode, setSourceMapRange, setTextRange, SignatureDeclaration,
skipParentheses, some, SourceFile, startOnNewLine, Statement, SyntaxKind, TaggedTemplateExpression, TextRange,
Token, TransformationContext, TransformFlags, unwrapInnermostStatementOfLabel, VariableDeclaration,
@@ -751,21 +751,21 @@ export function transformES2018(context: TransformationContext): (x: SourceFile
setTextRange(
factory.createForStatement(
/*initializer*/ setEmitFlags(
setTextRange(
factory.createVariableDeclarationList([
factory.createVariableDeclaration(nonUserCode, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createTrue()),
setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
factory.createVariableDeclaration(result)
]),
node.expression
),
EmitFlags.NoHoisting
setTextRange(
factory.createVariableDeclarationList([
factory.createVariableDeclaration(nonUserCode, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createTrue()),
setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
factory.createVariableDeclaration(result)
]),
node.expression
),
EmitFlags.NoHoisting
),
/*condition*/ factory.inlineExpressions([
factory.createAssignment(result, createDownlevelAwait(callNext)),
factory.createAssignment(done, getDone),
factory.createLogicalNot(done)
]),
factory.createAssignment(result, createDownlevelAwait(callNext)),
factory.createAssignment(done, getDone),
factory.createLogicalNot(done)
]),
/*incrementor*/ undefined,
/*statement*/ convertForOfStatementHead(node, getValue, nonUserCode)
),
@@ -801,38 +801,38 @@ export function transformES2018(context: TransformationContext): (x: SourceFile
factory.createBlock([
factory.createTryStatement(
/*tryBlock*/ factory.createBlock([
setEmitFlags(
factory.createIfStatement(
factory.createLogicalAnd(
factory.createLogicalAnd(
factory.createLogicalNot(nonUserCode),
factory.createLogicalNot(done),
),
factory.createAssignment(
returnMethod,
factory.createPropertyAccessExpression(iterator, "return")
)
),
factory.createExpressionStatement(createDownlevelAwait(callReturn))
),
EmitFlags.SingleLine
)
]),
/*catchClause*/ undefined,
/*finallyBlock*/ setEmitFlags(
factory.createBlock([
setEmitFlags(
factory.createIfStatement(
factory.createLogicalAnd(
factory.createLogicalAnd(
factory.createLogicalNot(nonUserCode),
factory.createLogicalNot(done),
),
factory.createAssignment(
returnMethod,
factory.createPropertyAccessExpression(iterator, "return")
)
),
factory.createExpressionStatement(createDownlevelAwait(callReturn))
errorRecord,
factory.createThrowStatement(
factory.createPropertyAccessExpression(errorRecord, "error")
)
),
EmitFlags.SingleLine
)
]),
/*catchClause*/ undefined,
/*finallyBlock*/ setEmitFlags(
factory.createBlock([
setEmitFlags(
factory.createIfStatement(
errorRecord,
factory.createThrowStatement(
factory.createPropertyAccessExpression(errorRecord, "error")
)
),
EmitFlags.SingleLine
)
]),
EmitFlags.SingleLine
)
EmitFlags.SingleLine
)
)
])
);
@@ -1051,7 +1051,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile
factory.createToken(SyntaxKind.AsteriskToken),
node.name && factory.getGeneratedNameForNode(node.name),
/*typeParameters*/ undefined,
/*parameters*/ [],
/*parameters*/[],
/*type*/ undefined,
factory.updateBlock(
node.body!,
+3 -3
View File
@@ -2,14 +2,14 @@ import {
AccessorDeclaration, addEmitHelpers, addSyntheticTrailingComment, ArrayLiteralExpression, Associativity,
BinaryExpression, Block, BreakStatement, Bundle, CallExpression, CaseClause, chainBundle, CommaListExpression,
ConditionalExpression, ContinueStatement, createExpressionForObjectLiteralElementLike, Debug, DoStatement,
ElementAccessExpression, EmitFlags, EmitHint, ESMap, Expression, ExpressionStatement, forEach, ForInStatement,
ElementAccessExpression, EmitFlags, EmitHint, Expression, ExpressionStatement, forEach, ForInStatement,
ForStatement, FunctionDeclaration, FunctionExpression, getEmitFlags, getEmitScriptTarget,
getExpressionAssociativity, getInitializedVariables, getNonAssignmentOperatorForCompoundAssignment, getOriginalNode,
getOriginalNodeId, Identifier, idText, IfStatement, InitializedVariableDeclaration,
insertStatementsAfterStandardPrologue, isBinaryExpression, isBlock, isCompoundAssignment, isExpression,
isFunctionLikeDeclaration, isGeneratedIdentifier, isIdentifier, isImportCall, isLeftHandSideExpression,
isLogicalOperator, isObjectLiteralElementLike, isStatement, isVariableDeclarationList, LabeledStatement,
lastOrUndefined, LeftHandSideExpression, LiteralExpression, map, Map, Mutable, NewExpression, Node, NodeArray,
lastOrUndefined, LeftHandSideExpression, LiteralExpression, map, Mutable, NewExpression, Node, NodeArray,
NumericLiteral, ObjectLiteralElementLike, ObjectLiteralExpression, PropertyAccessExpression, reduceLeft,
ReturnStatement, setCommentRange, setEmitFlags, setOriginalNode, setParent, setSourceMapRange, setTextRange,
SourceFile, startOnNewLine, Statement, SwitchStatement, SyntaxKind, TextRange, ThrowStatement,
@@ -263,7 +263,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF
const previousOnSubstituteNode = context.onSubstituteNode;
context.onSubstituteNode = onSubstituteNode;
let renamedCatchVariables: ESMap<string, boolean>;
let renamedCatchVariables: Map<string, boolean>;
let renamedCatchVariableDeclarations: Identifier[];
let inGeneratorFunctionBody: boolean;
+2 -2
View File
@@ -7,7 +7,7 @@ import {
isIntrinsicJsxName, isJsxAttribute, isJsxElement, isJsxFragment, isJsxSelfClosingElement, isJsxSpreadAttribute,
isLineBreak, isSourceFile, isStringDoubleQuoted, isWhiteSpaceSingleLine, JsxAttribute, JsxAttributeValue, JsxChild,
JsxElement, JsxEmit, JsxExpression, JsxFragment, JsxOpeningFragment, JsxOpeningLikeElement, JsxSelfClosingElement,
JsxSpreadAttribute, JsxText, length, map, Map, mapDefined, Node, NodeFlags, PropertyAssignment, ScriptTarget,
JsxSpreadAttribute, JsxText, length, map, mapDefined, Node, NodeFlags, PropertyAssignment, ScriptTarget,
setParentRecursive, setTextRange, singleOrUndefined, SourceFile, spanMap, SpreadAssignment, startOnNewLine,
Statement, StringLiteral, SyntaxKind, TextRange, TransformationContext, TransformFlags, utf16EncodeAsString,
VariableDeclaration, visitEachChild, visitNode, VisitResult,
@@ -18,7 +18,7 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B
interface PerFileState {
importSpecifier?: string;
filenameDeclaration?: VariableDeclaration & { name: Identifier; };
utilizedImplicitRuntimeImports?: Map<Map<ImportSpecifier>>;
utilizedImplicitRuntimeImports?: Map<string, Map<string, ImportSpecifier>>;
}
const {
@@ -1,10 +1,10 @@
import {
addRange, append, Bundle, chainBundle, createEmptyExports, createExternalHelpersImportDeclarationIfNeeded, Debug, EmitFlags,
EmitHint, ESMap, ExportAssignment, ExportDeclaration, Expression, GeneratedIdentifierFlags, getEmitFlags,
EmitHint, ExportAssignment, ExportDeclaration, Expression, GeneratedIdentifierFlags, getEmitFlags,
getEmitModuleKind, getEmitScriptTarget, getExternalModuleNameLiteral, hasSyntacticModifier, Identifier, idText,
ImportDeclaration, ImportEqualsDeclaration, insertStatementsAfterCustomPrologue,
isExportNamespaceAsDefaultDeclaration, isExternalModule, isExternalModuleImportEqualsDeclaration,
isExternalModuleIndicator, isIdentifier, isNamespaceExport, isSourceFile, isStatement, Map, ModifierFlags,
isExternalModuleIndicator, isIdentifier, isNamespaceExport, isSourceFile, isStatement, ModifierFlags,
ModuleKind, Node, NodeFlags, ScriptTarget, setOriginalNode, setTextRange, singleOrMany, some, SourceFile, Statement,
SyntaxKind, TransformationContext, VariableStatement, visitEachChild, visitNodes, VisitResult,
} from "../../_namespaces/ts";
@@ -26,7 +26,7 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S
context.enableEmitNotification(SyntaxKind.SourceFile);
context.enableSubstitution(SyntaxKind.Identifier);
let helperNameSubstitutions: ESMap<string, Identifier> | undefined;
let helperNameSubstitutions: Map<string, Identifier> | undefined;
let currentSourceFile: SourceFile | undefined;
let importRequireStatements: [ImportDeclaration, VariableStatement] | undefined;
return chainBundle(context, transformSourceFile);
+1 -1
View File
@@ -14,7 +14,7 @@ import {
isHeritageClause, isIdentifier, isImportCall, isImportClause, isImportMeta, isImportSpecifier, isLocalName,
isModifierLike, isModuleOrEnumDeclaration, isNamedExports, isObjectLiteralExpression, isOmittedExpression,
isParameterDeclaration, isPrefixUnaryExpression, isPropertyAssignment, isShorthandPropertyAssignment,
isSpreadElement, isStatement, isStringLiteral, isVariableDeclarationList, LabeledStatement, map, Map,
isSpreadElement, isStatement, isStringLiteral, isVariableDeclarationList, LabeledStatement, map,
MergeDeclarationMarker, MetaProperty, ModifierFlags, moveEmitHelpers, Node, NodeFlags, ObjectLiteralElementLike,
outFile, ParenthesizedExpression, PartiallyEmittedExpression, PostfixUnaryExpression, PrefixUnaryExpression,
PropertyAssignment, setCommentRange, setEmitFlags, setTextRange, ShorthandPropertyAssignment, singleOrMany, some,
+1 -1
View File
@@ -21,7 +21,7 @@ import {
isNamespaceExport, isObjectLiteralElement, isParameterPropertyDeclaration, isPrivateIdentifier,
isPropertyAccessExpression, isPropertyName, isShorthandPropertyAssignment, isSimpleInlineableExpression,
isSourceFile, isStatement, JsxOpeningElement, JsxSelfClosingElement, lastOrUndefined, LeftHandSideExpression, map,
Map, mapDefined, MethodDeclaration, ModifierFlags, ModifierLike, modifierToFlag, ModuleBlock, ModuleDeclaration,
mapDefined, MethodDeclaration, ModifierFlags, ModifierLike, modifierToFlag, ModuleBlock, ModuleDeclaration,
ModuleKind, moveRangePastDecorators, moveRangePastModifiers, moveRangePos, NamedExportBindings, NamedExports,
NamedImportBindings, NamespaceExport, NewExpression, Node, NodeFlags, nodeIsMissing, NonNullExpression,
ObjectLiteralElementLike, ObjectLiteralExpression, OuterExpressionKinds, ParameterDeclaration,
+4 -4
View File
@@ -2,7 +2,7 @@ import {
AccessorDeclaration, AllDecorators, append, BinaryOperator, BindingElement, Bundle, cast, ClassDeclaration,
ClassElement, ClassExpression, ClassLikeDeclaration, ClassStaticBlockDeclaration, CompilerOptions,
CompoundAssignmentOperator, CoreTransformationContext, createExternalHelpersImportDeclarationIfNeeded,
createMultiMap, Decorator, EmitResolver, ESMap, ExportAssignment, ExportDeclaration, ExportSpecifier, Expression,
createMultiMap, Decorator, EmitResolver, ExportAssignment, ExportDeclaration, ExportSpecifier, Expression,
filter, FunctionDeclaration, FunctionLikeDeclaration, getAllAccessorDeclarations, getDecorators,
getFirstConstructorWithBody, getNamespaceDeclarationNode, getNodeId, getOriginalNode, hasDecorators,
hasStaticModifier, hasSyntacticModifier, Identifier, idText, ImportDeclaration, ImportEqualsDeclaration,
@@ -10,7 +10,7 @@ import {
isBindingPattern, isClassStaticBlockDeclaration, isDefaultImport, isExpressionStatement, isGeneratedIdentifier,
isIdentifier, isKeyword, isMethodOrAccessor, isNamedExports, isNamedImports, isOmittedExpression,
isPrivateIdentifier, isPropertyDeclaration, isStatic, isStringLiteralLike, isSuperCall, LogicalOperatorOrHigher,
map, Map, MethodDeclaration, ModifierFlags, NamedImportBindings, NamespaceExport, Node, NodeArray,
map, MethodDeclaration, ModifierFlags, NamedImportBindings, NamespaceExport, Node, NodeArray,
parameterIsThisKeyword, PrivateIdentifierAccessorDeclaration, PrivateIdentifierAutoAccessorPropertyDeclaration,
PrivateIdentifierMethodDeclaration, PropertyDeclaration, skipParentheses, some, SourceFile, Statement, SuperCall, SyntaxKind,
TransformationContext, VariableDeclaration, VariableStatement,
@@ -26,7 +26,7 @@ export function getOriginalNodeId(node: Node) {
export interface ExternalModuleInfo {
externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]; // imports of other external modules
externalHelpersImportDeclaration: ImportDeclaration | undefined; // import of external helpers
exportSpecifiers: ESMap<string, ExportSpecifier[]>; // file-local export specifiers by name (no reexports)
exportSpecifiers: Map<string, ExportSpecifier[]>; // file-local export specifiers by name (no reexports)
exportedBindings: Identifier[][]; // exported names of local declarations
exportedNames: Identifier[] | undefined; // all exported names in the module, both local and reexported
exportEquals: ExportAssignment | undefined; // an export= declaration if one was present
@@ -244,7 +244,7 @@ export function collectExternalModuleInfo(context: TransformationContext, source
}
}
function collectExportedVariableInfo(decl: VariableDeclaration | BindingElement, uniqueExports: ESMap<string, boolean>, exportedNames: Identifier[] | undefined) {
function collectExportedVariableInfo(decl: VariableDeclaration | BindingElement, uniqueExports: Map<string, boolean>, exportedNames: Identifier[] | undefined) {
if (isBindingPattern(decl.name)) {
for (const element of decl.name.elements) {
if (!isOmittedExpression(element)) {
+28 -28
View File
@@ -8,20 +8,20 @@ import {
createTypeReferenceDirectiveResolutionCache, createWatchFactory, createWatchHost, CustomTransformers, Debug,
Diagnostic, DiagnosticCollection, DiagnosticMessage, DiagnosticReporter, Diagnostics,
EmitAndSemanticDiagnosticsBuilderProgram, emitFilesAndReportErrors, EmitResult, emitUsingBuildInfo, emptyArray,
ESMap, ExitStatus, ExtendedConfigCacheEntry, FileWatcher, FileWatcherCallback, findIndex,
ExitStatus, ExtendedConfigCacheEntry, FileWatcher, FileWatcherCallback, findIndex,
flattenDiagnosticMessageText, forEach, ForegroundColorEscapeSequences, formatColorAndReset, getAllProjectOutputs,
getBuildInfoFileVersionMap, GetCanonicalFileName, getConfigFileParsingDiagnostics, getDirectoryPath, getEntries,
getErrorCountForSummary, getFileNamesFromConfigSpecs, getFilesInErrorForSummary, getFirstProjectOutput,
getLocaleTimeString, getNormalizedAbsolutePath, getParsedCommandLineOfConfigFile, getPendingEmitKind,
getSourceFileVersionAsHashFromText, getTsBuildInfoEmitOutputFilePath, getWatchErrorSummaryDiagnosticMessage,
hasProperty, identity, isArray, isIgnoredFileFromWildCardWatching, isIncrementalCompilation, isString, listFiles,
loadWithModeAwareCache, loadWithTypeDirectiveCache, map, Map, maybeBind, missingFileModifiedTime, ModuleKind,
loadWithModeAwareCache, loadWithTypeDirectiveCache, map, maybeBind, missingFileModifiedTime, ModuleKind,
ModuleResolutionCache, mutateMap, mutateMapSkippingNewValues, noop, outFile, OutputFile, ParseConfigFileHost,
parseConfigHostFromCompilerHostLike, ParsedCommandLine, Path, PollingInterval, Program, ProgramBuildInfo,
ProgramBundleEmitBuildInfo, ProgramHost, ProgramMultiFileEmitBuildInfo, readBuilderProgram, ReadBuildProgramHost,
resolveConfigFileProjectName, ResolvedConfigFileName, ResolvedProjectReference, ResolvedTypeReferenceDirective,
resolveModuleName, resolvePath, resolveProjectReferencePath, resolveTypeReferenceDirective, returnUndefined,
SemanticDiagnosticsBuilderProgram, Set, setGetSourceFileAsHashVersioned, SharedExtendedConfigFileWatcher, some,
SemanticDiagnosticsBuilderProgram, setGetSourceFileAsHashVersioned, SharedExtendedConfigFileWatcher, some,
SourceFile, Status, sys, System, TypeReferenceDirectiveResolutionCache, unorderedRemoveItem,
updateErrorForNoInputFiles, updateSharedExtendedConfigFileWatcher, updateWatchingWildcardDirectories,
UpToDateStatus, UpToDateStatusType, version, WatchFactory, WatchHost, WatchOptions, WatchStatusReporter, WatchType,
@@ -89,7 +89,7 @@ enum BuildResultFlags {
/** @internal */
export type ResolvedConfigFilePath = ResolvedConfigFileName & Path;
function getOrCreateValueFromConfigFileMap<T>(configFileMap: ESMap<ResolvedConfigFilePath, T>, resolved: ResolvedConfigFilePath, createT: () => T): T {
function getOrCreateValueFromConfigFileMap<T>(configFileMap: Map<ResolvedConfigFilePath, T>, resolved: ResolvedConfigFilePath, createT: () => T): T {
const existingValue = configFileMap.get(resolved);
let newValue: T | undefined;
if (!existingValue) {
@@ -99,7 +99,7 @@ function getOrCreateValueFromConfigFileMap<T>(configFileMap: ESMap<ResolvedConfi
return existingValue || newValue!;
}
function getOrCreateValueMapFromConfigFileMap<K extends string, V>(configFileMap: ESMap<ResolvedConfigFilePath, ESMap<K, V>>, resolved: ResolvedConfigFilePath): ESMap<K, V> {
function getOrCreateValueMapFromConfigFileMap<K extends string, V>(configFileMap: Map<ResolvedConfigFilePath, Map<K, V>>, resolved: ResolvedConfigFilePath): Map<K, V> {
return getOrCreateValueFromConfigFileMap(configFileMap, resolved, () => new Map());
}
@@ -280,17 +280,17 @@ interface SolutionBuilderState<T extends BuilderProgram = BuilderProgram> extend
readonly rootNames: readonly string[];
readonly baseWatchOptions: WatchOptions | undefined;
readonly resolvedConfigFilePaths: ESMap<string, ResolvedConfigFilePath>;
readonly configFileCache: ESMap<ResolvedConfigFilePath, ConfigFileCacheEntry>;
readonly resolvedConfigFilePaths: Map<string, ResolvedConfigFilePath>;
readonly configFileCache: Map<ResolvedConfigFilePath, ConfigFileCacheEntry>;
/** Map from config file name to up-to-date status */
readonly projectStatus: ESMap<ResolvedConfigFilePath, UpToDateStatus>;
readonly extendedConfigCache: ESMap<string, ExtendedConfigCacheEntry>;
readonly buildInfoCache: ESMap<ResolvedConfigFilePath, BuildInfoCacheEntry>;
readonly projectStatus: Map<ResolvedConfigFilePath, UpToDateStatus>;
readonly extendedConfigCache: Map<string, ExtendedConfigCacheEntry>;
readonly buildInfoCache: Map<ResolvedConfigFilePath, BuildInfoCacheEntry>;
readonly builderPrograms: ESMap<ResolvedConfigFilePath, T>;
readonly diagnostics: ESMap<ResolvedConfigFilePath, readonly Diagnostic[]>;
readonly projectPendingBuild: ESMap<ResolvedConfigFilePath, ConfigFileProgramReloadLevel>;
readonly projectErrorsReported: ESMap<ResolvedConfigFilePath, true>;
readonly builderPrograms: Map<ResolvedConfigFilePath, T>;
readonly diagnostics: Map<ResolvedConfigFilePath, readonly Diagnostic[]>;
readonly projectPendingBuild: Map<ResolvedConfigFilePath, ConfigFileProgramReloadLevel>;
readonly projectErrorsReported: Map<ResolvedConfigFilePath, true>;
readonly compilerHost: CompilerHost & ReadBuildProgramHost;
readonly moduleResolutionCache: ModuleResolutionCache | undefined;
@@ -307,15 +307,15 @@ interface SolutionBuilderState<T extends BuilderProgram = BuilderProgram> extend
// Watch state
readonly watch: boolean;
readonly allWatchedWildcardDirectories: ESMap<ResolvedConfigFilePath, ESMap<string, WildcardDirectoryWatcher>>;
readonly allWatchedInputFiles: ESMap<ResolvedConfigFilePath, ESMap<Path, FileWatcher>>;
readonly allWatchedConfigFiles: ESMap<ResolvedConfigFilePath, FileWatcher>;
readonly allWatchedExtendedConfigFiles: ESMap<Path, SharedExtendedConfigFileWatcher<ResolvedConfigFilePath>>;
readonly allWatchedPackageJsonFiles: ESMap<ResolvedConfigFilePath, ESMap<Path, FileWatcher>>;
readonly filesWatched: ESMap<Path, FileWatcherWithModifiedTime | Date>;
readonly outputTimeStamps: ESMap<ResolvedConfigFilePath, ESMap<Path, Date>>;
readonly allWatchedWildcardDirectories: Map<ResolvedConfigFilePath, Map<string, WildcardDirectoryWatcher>>;
readonly allWatchedInputFiles: Map<ResolvedConfigFilePath, Map<Path, FileWatcher>>;
readonly allWatchedConfigFiles: Map<ResolvedConfigFilePath, FileWatcher>;
readonly allWatchedExtendedConfigFiles: Map<Path, SharedExtendedConfigFileWatcher<ResolvedConfigFilePath>>;
readonly allWatchedPackageJsonFiles: Map<ResolvedConfigFilePath, Map<Path, FileWatcher>>;
readonly filesWatched: Map<Path, FileWatcherWithModifiedTime | Date>;
readonly outputTimeStamps: Map<ResolvedConfigFilePath, Map<Path, Date>>;
readonly lastCachedPackageJsonLookups: ESMap<ResolvedConfigFilePath, readonly (readonly [Path, object | boolean])[] | undefined>;
readonly lastCachedPackageJsonLookups: Map<ResolvedConfigFilePath, readonly (readonly [Path, object | boolean])[] | undefined>;
timerToBuildInvalidatedProject: any;
reportFileChangeDetected: boolean;
@@ -1033,7 +1033,7 @@ function createBuildOrUpdateInvalidedProject<T extends BuilderProgram>(
const emittedOutputs = new Map<Path, string>();
const options = program.getCompilerOptions();
const isIncremental = isIncrementalCompilation(options);
let outputTimeStampMap: ESMap<Path, Date> | undefined;
let outputTimeStampMap: Map<Path, Date> | undefined;
let now: Date | undefined;
outputFiles.forEach(({ name, text, writeByteOrderMark, data }) => {
const path = toPath(state, name);
@@ -1081,7 +1081,7 @@ function createBuildOrUpdateInvalidedProject<T extends BuilderProgram>(
function finishEmit(
emitterDiagnostics: DiagnosticCollection,
emittedOutputs: ESMap<Path, string>,
emittedOutputs: Map<Path, string>,
oldestOutputFileName: string,
resultFlags: BuildResultFlags
) {
@@ -1618,7 +1618,7 @@ function getUpToDateStatusWorker(state: SolutionBuilderState, project: ParsedCom
let oldestOutputFileTime = maximumDate;
let buildInfoTime: Date | undefined;
let buildInfoProgram: ProgramBuildInfo | undefined;
let buildInfoVersionMap: ESMap<Path, string> | undefined;
let buildInfoVersionMap: Map<Path, string> | undefined;
if (buildInfoPath) {
const buildInfoCacheEntry = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath);
buildInfoTime = buildInfoCacheEntry?.modifiedTime || ts.getModifiedTime(host, buildInfoPath);
@@ -1871,7 +1871,7 @@ function updateOutputTimestampsWorker(
proj: ParsedCommandLine,
projectPath: ResolvedConfigFilePath,
verboseMessage: DiagnosticMessage,
skipOutputs?: ESMap<Path, string>
skipOutputs?: Map<Path, string>
) {
if (proj.options.noEmit) return;
let now: Date | undefined;
@@ -1982,7 +1982,7 @@ function queueReferencingProjects(
}
break;
}
// falls through
// falls through
case UpToDateStatusType.UpToDateWithInputFileText:
case UpToDateStatusType.UpToDateWithUpstreamTypes:
@@ -2193,7 +2193,7 @@ function watchExtendedConfigFiles(state: SolutionBuilderState, resolvedPath: Res
state,
extendedConfigFileName,
() => state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)?.projects.forEach(projectConfigFilePath =>
invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ConfigFileProgramReloadLevel.Full)),
invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ConfigFileProgramReloadLevel.Full)),
PollingInterval.High,
parsed?.watchOptions,
WatchType.ExtendedConfigFile,
+30 -30
View File
@@ -1,7 +1,7 @@
import {
BaseNodeFactory, CreateSourceFileOptions, EmitHelperFactory, ESMap, Map, MapLike, ModeAwareCache,
BaseNodeFactory, CreateSourceFileOptions, EmitHelperFactory, MapLike, ModeAwareCache,
ModuleResolutionCache, MultiMap, NodeFactoryFlags, OptionsNameMap, PackageJsonInfo, PackageJsonInfoCache, Pattern,
ProgramBuildInfo, Push, ReadonlyESMap, ReadonlySet, Set, SymlinkCache,
ProgramBuildInfo, Push, SymlinkCache,
} from "./_namespaces/ts";
// branded string type used to store absolute, normalized and canonicalized paths
@@ -4013,7 +4013,7 @@ export interface SourceFile extends Declaration {
// this map is used by transpiler to supply alternative names for dependencies (i.e. in case of bundling)
/** @internal */
renamedDependencies?: ReadonlyESMap<string, string>;
renamedDependencies?: ReadonlyMap<string, string>;
/**
* lib.d.ts should have a reference comment like
@@ -4071,7 +4071,7 @@ export interface SourceFile extends Declaration {
// JS identifier-declarations that are intended to merge with globals
/** @internal */ jsGlobalAugmentations?: SymbolTable;
/** @internal */ identifiers: ESMap<string, string>; // Map from a string to an interned string
/** @internal */ identifiers: Map<string, string>; // Map from a string to an interned string
/** @internal */ nodeCount: number;
/** @internal */ identifierCount: number;
/** @internal */ symbolCount: number;
@@ -4421,7 +4421,7 @@ export interface Program extends ScriptReferenceHost {
/** @internal */
getModuleResolutionCache(): ModuleResolutionCache | undefined;
/** @internal */
getFilesByNameMap(): ESMap<string, SourceFile | false | undefined>;
getFilesByNameMap(): Map<string, SourceFile | false | undefined>;
/**
* Emits the JavaScript and declaration files. If targetSourceFile is not specified, then
@@ -4484,7 +4484,7 @@ export interface Program extends ScriptReferenceHost {
*
* @internal
*/
sourceFileToPackageName: ESMap<Path, string>;
sourceFileToPackageName: Map<Path, string>;
/**
* Set of all source files that some other source file redirects to.
*
@@ -4536,7 +4536,7 @@ export interface Program extends TypeCheckerHost, ModuleSpecifierResolutionHost
}
/** @internal */
export type RedirectTargetsMap = ReadonlyESMap<Path, readonly string[]>;
export type RedirectTargetsMap = ReadonlyMap<Path, readonly string[]>;
export interface ResolvedProjectReference {
commandLine: ParsedCommandLine;
@@ -5452,7 +5452,7 @@ export interface Symbol {
/** @internal */ isReferenced?: SymbolFlags; // True if the symbol is referenced elsewhere. Keeps track of the meaning of a reference in case a symbol is both a type parameter and parameter.
/** @internal */ isReplaceableByMethod?: boolean; // Can this Javascript class property be replaced by a method symbol?
/** @internal */ isAssigned?: boolean; // True if the symbol is a parameter with assignments
/** @internal */ assignmentDeclarationMembers?: ESMap<number, Declaration>; // detected late-bound assignment declarations associated with the symbol
/** @internal */ assignmentDeclarationMembers?: Map<number, Declaration>; // detected late-bound assignment declarations associated with the symbol
}
/** @internal */
@@ -5467,10 +5467,10 @@ export interface SymbolLinks {
declaredType?: Type; // Type of class, interface, enum, type alias, or type parameter
typeParameters?: TypeParameter[]; // Type parameters of type alias (undefined if non-generic)
outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type
instantiations?: ESMap<string, Type>; // Instantiations of generic type alias (undefined if non-generic)
instantiations?: Map<string, Type>; // Instantiations of generic type alias (undefined if non-generic)
aliasSymbol?: Symbol; // Alias associated with generic type alias instantiation
aliasTypeArguments?: readonly Type[] // Alias type arguments (if any)
inferredClassSymbol?: ESMap<SymbolId, TransientSymbol>; // Symbol of an inferred ES5 constructor function
inferredClassSymbol?: Map<SymbolId, TransientSymbol>; // Symbol of an inferred ES5 constructor function
mapper?: TypeMapper; // Type mapper for instantiation alias
referenced?: boolean; // True if alias symbol has been referenced as a value that can be emitted
constEnumReferenced?: boolean; // True if alias symbol resolves to a const enum and is referenced as a value ('referenced' will be false)
@@ -5489,9 +5489,9 @@ export interface SymbolLinks {
enumKind?: EnumKind; // Enum declaration classification
originatingImport?: ImportDeclaration | ImportCall; // Import declaration which produced the symbol, present if the symbol is marked as uncallable but had call signatures in `resolveESModuleSymbol`
lateSymbol?: Symbol; // Late-bound symbol for a computed property
specifierCache?: ESMap<string, string>; // For symbols corresponding to external modules, a cache of incoming path -> module specifier name mappings
specifierCache?: Map<string, string>; // For symbols corresponding to external modules, a cache of incoming path -> module specifier name mappings
extendedContainers?: Symbol[]; // Containers (other than the parent) which this symbol is aliased in
extendedContainersByFile?: ESMap<NodeId, Symbol[]>; // Containers (other than the parent) which this symbol is aliased in
extendedContainersByFile?: Map<NodeId, Symbol[]>; // Containers (other than the parent) which this symbol is aliased in
variances?: VarianceFlags[]; // Alias symbol type argument variance cache
deferralConstituents?: Type[]; // Calculated list of constituents for a deferred type
deferralWriteConstituents?: Type[]; // Constituents of a deferred `writeType`
@@ -5500,8 +5500,8 @@ export interface SymbolLinks {
typeOnlyDeclaration?: TypeOnlyAliasDeclaration | false; // First resolved alias declaration that makes the symbol only usable in type constructs
isConstructorDeclaredProperty?: boolean; // Property declared through 'this.x = ...' assignment in constructor
tupleLabelDeclaration?: NamedTupleMember | ParameterDeclaration; // Declaration associated with the tuple's label
accessibleChainCache?: ESMap<string, Symbol[] | undefined>;
filteredIndexSymbolCache?: ESMap<string, Symbol> //Symbol with applicable declarations
accessibleChainCache?: Map<string, Symbol[] | undefined>;
filteredIndexSymbolCache?: Map<string, Symbol> //Symbol with applicable declarations
}
/** @internal */
@@ -5587,11 +5587,11 @@ export const enum InternalSymbolName {
export type __String = (string & { __escapedIdentifier: void }) | (void & { __escapedIdentifier: void }) | InternalSymbolName; // eslint-disable-line @typescript-eslint/naming-convention
/** ReadonlyMap where keys are `__String`s. */
export interface ReadonlyUnderscoreEscapedMap<T> extends ReadonlyESMap<__String, T> {
export interface ReadonlyUnderscoreEscapedMap<T> extends ReadonlyMap<__String, T> {
}
/** Map where keys are `__String`s. */
export interface UnderscoreEscapedMap<T> extends ESMap<__String, T>, ReadonlyUnderscoreEscapedMap<T> {
export interface UnderscoreEscapedMap<T> extends Map<__String, T> {
}
/** SymbolTable based on ES6 Map interface. */
@@ -5663,7 +5663,7 @@ export interface NodeLinks {
isExhaustive?: boolean | 0; // Is node an exhaustive switch statement (0 indicates in-process resolution)
skipDirectInference?: true; // Flag set by the API `getContextualType` call on a node when `Completions` is passed to force the checker to skip making inferences to a node's type
declarationRequiresScopeChange?: boolean; // Set by `useOuterVariableScopeInParameter` in checker when downlevel emit would change the name resolution scope inside of a parameter.
serializedTypes?: ESMap<string, TypeNode & {truncating?: boolean, addedLength: number}>; // Collection of types serialized at this location
serializedTypes?: Map<string, TypeNode & {truncating?: boolean, addedLength: number}>; // Collection of types serialized at this location
}
export const enum TypeFlags {
@@ -5982,7 +5982,7 @@ export interface DeferredTypeReference extends TypeReference {
/** @internal */
mapper?: TypeMapper;
/** @internal */
instantiations?: ESMap<string, Type>; // Instantiations of generic type alias (undefined if non-generic)
instantiations?: Map<string, Type>; // Instantiations of generic type alias (undefined if non-generic)
}
/** @internal */
@@ -6001,7 +6001,7 @@ export const enum VarianceFlags {
// Generic class and interface types
export interface GenericType extends InterfaceType, TypeReference {
/** @internal */
instantiations: ESMap<string, TypeReference>; // Generic instantiation cache
instantiations: Map<string, TypeReference>; // Generic instantiation cache
/** @internal */
variances?: VarianceFlags[]; // Variance of each type parameter
}
@@ -6062,7 +6062,7 @@ export interface UnionType extends UnionOrIntersectionType {
/** @internal */
keyPropertyName?: __String; // Property with unique unit type that exists in every object/intersection in union type
/** @internal */
constituentMap?: ESMap<TypeId, Type>; // Constituents keyed by unit type discriminants
constituentMap?: Map<TypeId, Type>; // Constituents keyed by unit type discriminants
}
export interface IntersectionType extends UnionOrIntersectionType {
@@ -6077,7 +6077,7 @@ export type StructuredType = ObjectType | UnionType | IntersectionType;
export interface AnonymousType extends ObjectType {
target?: AnonymousType; // Instantiation target
mapper?: TypeMapper; // Instantiation mapper
instantiations?: ESMap<string, Type>; // Instantiations of generic type alias (undefined if non-generic)
instantiations?: Map<string, Type>; // Instantiations of generic type alias (undefined if non-generic)
}
/** @internal */
@@ -6231,7 +6231,7 @@ export interface ConditionalRoot {
isDistributive: boolean;
inferTypeParameters?: TypeParameter[];
outerTypeParameters?: TypeParameter[];
instantiations?: Map<Type>;
instantiations?: Map<string, Type>;
aliasSymbol?: Symbol;
aliasTypeArguments?: Type[];
}
@@ -6348,7 +6348,7 @@ export interface Signature {
/** @internal */
isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison
/** @internal */
instantiations?: ESMap<string, Signature>; // Generic signature instantiation cache
instantiations?: Map<string, Signature>; // Generic signature instantiation cache
}
export const enum IndexKind {
@@ -6942,7 +6942,7 @@ export interface CreateProgramOptions {
/** @internal */
export interface CommandLineOptionBase {
name: string;
type: "string" | "number" | "boolean" | "object" | "list" | ESMap<string, number | string>; // a value of a primitive type, or an object literal mapping named values to actual values
type: "string" | "number" | "boolean" | "object" | "list" | Map<string, number | string>; // a value of a primitive type, or an object literal mapping named values to actual values
isFilePath?: boolean; // True if option value is a path or fileName
shortName?: string; // A short mnemonic for convenience - for instance, 'h' can be used in place of 'help'
description?: DiagnosticMessage; // The message describing what the command line switch does.
@@ -6985,7 +6985,7 @@ export interface CommandLineOptionOfBooleanType extends CommandLineOptionBase {
/** @internal */
export interface CommandLineOptionOfCustomType extends CommandLineOptionBase {
type: ESMap<string, number | string>; // an object literal mapping named values to actual values
type: Map<string, number | string>; // an object literal mapping named values to actual values
defaultValueDescription: number | string | undefined | DiagnosticMessage;
}
@@ -7006,7 +7006,7 @@ export interface DidYouMeanOptionsDiagnostics {
/** @internal */
export interface TsConfigOnlyOption extends CommandLineOptionBase {
type: "object";
elementOptions?: ESMap<string, CommandLineOption>;
elementOptions?: Map<string, CommandLineOption>;
extraKeyDiagnostics?: DidYouMeanOptionsDiagnostics;
}
@@ -9353,9 +9353,9 @@ export type PragmaPseudoMap = {[K in keyof ConcretePragmaSpecs]: {arguments: Pra
export type PragmaPseudoMapEntry = {[K in keyof PragmaPseudoMap]: {name: K, args: PragmaPseudoMap[K]}}[keyof PragmaPseudoMap];
/** @internal */
export interface ReadonlyPragmaMap extends ReadonlyESMap<string, PragmaPseudoMap[keyof PragmaPseudoMap] | PragmaPseudoMap[keyof PragmaPseudoMap][]> {
export interface ReadonlyPragmaMap extends ReadonlyMap<string, PragmaPseudoMap[keyof PragmaPseudoMap] | PragmaPseudoMap[keyof PragmaPseudoMap][]> {
get<TKey extends keyof PragmaPseudoMap>(key: TKey): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][];
forEach(action: <TKey extends keyof PragmaPseudoMap>(value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey) => void): void;
forEach(action: <TKey extends keyof PragmaPseudoMap>(value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey, map: ReadonlyPragmaMap) => void): void;
}
/**
@@ -9365,10 +9365,10 @@ export interface ReadonlyPragmaMap extends ReadonlyESMap<string, PragmaPseudoMap
*
* @internal
*/
export interface PragmaMap extends ESMap<string, PragmaPseudoMap[keyof PragmaPseudoMap] | PragmaPseudoMap[keyof PragmaPseudoMap][]>, ReadonlyPragmaMap {
export interface PragmaMap extends Map<string, PragmaPseudoMap[keyof PragmaPseudoMap] | PragmaPseudoMap[keyof PragmaPseudoMap][]>, ReadonlyPragmaMap {
set<TKey extends keyof PragmaPseudoMap>(key: TKey, value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]): this;
get<TKey extends keyof PragmaPseudoMap>(key: TKey): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][];
forEach(action: <TKey extends keyof PragmaPseudoMap>(value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey) => void): void;
forEach(action: <TKey extends keyof PragmaPseudoMap>(value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey, map: PragmaMap) => void): void;
}
/** @internal */
+16 -16
View File
@@ -19,7 +19,7 @@ import {
directorySeparator, DoStatement, DynamicNamedBinaryExpression, DynamicNamedDeclaration, ElementAccessExpression,
EmitFlags, EmitHost, EmitResolver, EmitTextWriter, emptyArray, ensurePathIsNonModuleName,
ensureTrailingDirectorySeparator, EntityName, EntityNameExpression, EntityNameOrEntityNameExpression,
EnumDeclaration, EqualityComparer, equalOwnProperties, EqualsToken, equateValues, escapeLeadingUnderscores, ESMap,
EnumDeclaration, EqualityComparer, equalOwnProperties, EqualsToken, equateValues, escapeLeadingUnderscores,
every, ExportAssignment, ExportDeclaration, ExportSpecifier, Expression, ExpressionStatement,
ExpressionWithTypeArguments, Extension, ExternalModuleReference, factory, FileExtensionInfo, fileExtensionIs,
fileExtensionIsOneOf, FileReference, FileWatcher, filter, find, findAncestor, findBestPatternMatch, findIndex,
@@ -63,7 +63,7 @@ import {
JSDocTemplateTag, JSDocTypedefTag, JsonSourceFile, JsxChild, JsxElement, JsxEmit, JsxFragment, JsxOpeningElement,
JsxOpeningLikeElement, JsxSelfClosingElement, JsxTagNameExpression, KeywordSyntaxKind, LabeledStatement,
LanguageVariant, last, lastOrUndefined, LateVisibilityPaintedStatement, length, LiteralImportTypeNode,
LiteralLikeElementAccessExpression, LiteralLikeNode, LogicalOrCoalescingAssignmentOperator, map, Map, mapDefined,
LiteralLikeElementAccessExpression, LiteralLikeNode, LogicalOrCoalescingAssignmentOperator, map, mapDefined,
MapLike, MemberName, MethodDeclaration, ModeAwareCache, ModifierFlags, ModifierLike, ModuleBlock, ModuleDeclaration,
ModuleDetectionKind, ModuleKind, ModuleResolutionKind, moduleResolutionOptionDeclarations, MultiMap,
NamedDeclaration, NamedExports, NamedImports, NamedImportsOrExports, NamespaceExport, NamespaceImport,
@@ -74,7 +74,7 @@ import {
parseConfigFileTextToJson, PartiallyEmittedExpression, Path, pathIsRelative, Pattern, PostfixUnaryExpression,
PrefixUnaryExpression, PrinterOptions, PrintHandlers, PrivateIdentifier, ProjectReference, PrologueDirective,
PropertyAccessEntityNameExpression, PropertyAccessExpression, PropertyAssignment, PropertyDeclaration, PropertyName,
PropertyNameLiteral, PseudoBigInt, QualifiedName, ReadonlyCollection, ReadonlyESMap, ReadonlyTextRange,
PropertyNameLiteral, PseudoBigInt, QualifiedName, ReadonlyCollection, ReadonlyTextRange,
removeTrailingDirectorySeparator, RequireOrImportCall, RequireVariableStatement, ResolvedModuleFull,
ResolvedTypeReferenceDirective, ReturnStatement, SatisfiesExpression, ScriptKind, ScriptTarget,
semanticDiagnosticsOptionDeclarations, SetAccessorDeclaration, ShorthandPropertyAssignment, Signature,
@@ -219,7 +219,7 @@ export function forEachAncestor<T>(node: Node, callback: (n: Node) => T | undefi
*
* @internal
*/
export function forEachEntry<K, V, U>(map: ReadonlyESMap<K, V>, callback: (value: V, key: K) => U | undefined): U | undefined {
export function forEachEntry<K, V, U>(map: ReadonlyMap<K, V>, callback: (value: V, key: K) => U | undefined): U | undefined {
const iterator = map.entries();
for (let iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
const [key, value] = iterResult.value;
@@ -252,7 +252,7 @@ export function forEachKey<K, T>(map: ReadonlyCollection<K>, callback: (key: K)
*
* @internal
*/
export function copyEntries<K, V>(source: ReadonlyESMap<K, V>, target: ESMap<K, V>): void {
export function copyEntries<K, V>(source: ReadonlyMap<K, V>, target: Map<K, V>): void {
source.forEach((value, key) => {
target.set(key, value);
});
@@ -6355,7 +6355,7 @@ export function compareDataObjects(dst: any, src: any): boolean {
*
* @internal
*/
export function clearMap<K, T>(map: { forEach: ESMap<K, T>["forEach"]; clear: ESMap<K, T>["clear"]; }, onDeleteValue: (valueInMap: T, key: K) => void) {
export function clearMap<K, T>(map: { forEach: Map<K, T>["forEach"]; clear: Map<K, T>["clear"]; }, onDeleteValue: (valueInMap: T, key: K) => void) {
// Remove all
map.forEach(onDeleteValue);
map.clear();
@@ -6380,8 +6380,8 @@ export interface MutateMapSkippingNewValuesOptions<K, T, U> {
* @internal
*/
export function mutateMapSkippingNewValues<K, T, U>(
map: ESMap<K, T>,
newMap: ReadonlyESMap<K, U>,
map: Map<K, T>,
newMap: ReadonlyMap<K, U>,
options: MutateMapSkippingNewValuesOptions<K, T, U>
) {
const { onDeleteValue, onExistingValue } = options;
@@ -6410,7 +6410,7 @@ export interface MutateMapOptions<K, T, U> extends MutateMapSkippingNewValuesOpt
*
* @internal
*/
export function mutateMap<K, T, U>(map: ESMap<K, T>, newMap: ReadonlyESMap<K, U>, options: MutateMapOptions<K, T, U>) {
export function mutateMap<K, T, U>(map: Map<K, T>, newMap: ReadonlyMap<K, U>, options: MutateMapOptions<K, T, U>) {
// Needs update
mutateMapSkippingNewValues(map, newMap, options);
@@ -6487,11 +6487,11 @@ export function getLastChild(node: Node): Node | undefined {
*
* @internal
*/
export function addToSeen<K>(seen: ESMap<K, true>, key: K): boolean;
export function addToSeen<K>(seen: Map<K, true>, key: K): boolean;
/** @internal */
export function addToSeen<K, T>(seen: ESMap<K, T>, key: K, value: T): boolean;
export function addToSeen<K, T>(seen: Map<K, T>, key: K, value: T): boolean;
/** @internal */
export function addToSeen<K, T>(seen: ESMap<K, T>, key: K, value: T = true as any): boolean {
export function addToSeen<K, T>(seen: Map<K, T>, key: K, value: T = true as any): boolean {
if (seen.has(key)) {
return false;
}
@@ -7286,11 +7286,11 @@ export interface SymlinkedDirectory {
/** @internal */
export interface SymlinkCache {
/** Gets a map from symlink to realpath. Keys have trailing directory separators. */
getSymlinkedDirectories(): ReadonlyESMap<Path, SymlinkedDirectory | false> | undefined;
getSymlinkedDirectories(): ReadonlyMap<Path, SymlinkedDirectory | false> | undefined;
/** Gets a map from realpath to symlinks. Keys have trailing directory separators. */
getSymlinkedDirectoriesByRealpath(): MultiMap<Path, string> | undefined;
/** Gets a map from symlink to realpath */
getSymlinkedFiles(): ReadonlyESMap<Path, string> | undefined;
getSymlinkedFiles(): ReadonlyMap<Path, string> | undefined;
setSymlinkedDirectory(symlink: string, real: SymlinkedDirectory | false): void;
setSymlinkedFile(symlinkPath: Path, real: string): void;
/**
@@ -7309,9 +7309,9 @@ export interface SymlinkCache {
/** @internal */
export function createSymlinkCache(cwd: string, getCanonicalFileName: GetCanonicalFileName): SymlinkCache {
let symlinkedDirectories: ESMap<Path, SymlinkedDirectory | false> | undefined;
let symlinkedDirectories: Map<Path, SymlinkedDirectory | false> | undefined;
let symlinkedDirectoriesByRealpath: MultiMap<Path, string> | undefined;
let symlinkedFiles: ESMap<Path, string> | undefined;
let symlinkedFiles: Map<Path, string> | undefined;
let hasProcessedResolutions = false;
return {
getSymlinkedFiles: () => symlinkedFiles,
+9 -9
View File
@@ -12,7 +12,7 @@ import {
getEmitScriptTarget, getLineAndCharacterOfPosition, getNewLineCharacter, getNormalizedAbsolutePath,
getParsedCommandLineOfConfigFile, getPatternFromSpec, getReferencedFileLocation, getRegexFromPattern,
getRelativePathFromDirectory, getWatchFactory, HasCurrentDirectory, isExternalOrCommonJsModule, isLineBreak,
isReferencedFile, isReferenceFileLocation, isString, last, Map, maybeBind, memoize, ModuleKind, noop, normalizePath,
isReferencedFile, isReferenceFileLocation, isString, last, maybeBind, memoize, ModuleKind, noop, normalizePath,
outFile, packageIdToString, ParseConfigFileHost, ParsedCommandLine, pathIsAbsolute, Program, ProgramHost, ProjectReference,
ReportEmitErrorSummary, ReportFileInError, sortAndDeduplicateDiagnostics, SortedReadonlyArray, SourceFile, sourceMapCommentRegExp,
sourceMapCommentRegExpDontCareLineStart, sys, System, targetOptionDeclaration, WatchCompilerHost,
@@ -120,7 +120,7 @@ export function createWatchStatusReporter(system: System, pretty?: boolean): Wat
*
* @internal
*/
export function parseConfigFileWithSystem(configFileName: string, optionsToExtend: CompilerOptions, extendedConfigCache: Map<ExtendedConfigCacheEntry> | undefined, watchOptionsToExtend: WatchOptions | undefined, system: System, reportDiagnostic: DiagnosticReporter): ParsedCommandLine | undefined {
export function parseConfigFileWithSystem(configFileName: string, optionsToExtend: CompilerOptions, extendedConfigCache: Map<string, ExtendedConfigCacheEntry> | undefined, watchOptionsToExtend: WatchOptions | undefined, system: System, reportDiagnostic: DiagnosticReporter): ParsedCommandLine | undefined {
const host: ParseConfigFileHost = system as any;
host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic);
const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend);
@@ -137,17 +137,17 @@ export function getErrorCountForSummary(diagnostics: readonly Diagnostic[]) {
export function getFilesInErrorForSummary(diagnostics: readonly Diagnostic[]): (ReportFileInError | undefined)[] {
const filesInError =
filter(diagnostics, diagnostic => diagnostic.category === DiagnosticCategory.Error)
.map(
errorDiagnostic => {
if(errorDiagnostic.file === undefined) return;
return `${errorDiagnostic.file.fileName}`;
});
.map(
errorDiagnostic => {
if (errorDiagnostic.file === undefined) return;
return `${errorDiagnostic.file.fileName}`;
});
return filesInError.map((fileName: string) => {
const diagnosticForFileName = find(diagnostics, diagnostic =>
diagnostic.file !== undefined && diagnostic.file.fileName === fileName
);
if(diagnosticForFileName !== undefined) {
if (diagnosticForFileName !== undefined) {
const { line } = getLineAndCharacterOfPosition(diagnosticForFileName.file!, diagnosticForFileName.start!);
return {
fileName,
@@ -713,7 +713,7 @@ export function getSourceFileVersionAsHashFromText(host: Pick<CompilerHost, "cre
break;
}
// If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
else if (!line.match(whitespaceOrMapCommentRegExp)){
else if (!line.match(whitespaceOrMapCommentRegExp)) {
break;
}
lineEnd = lineStart;
+8 -8
View File
@@ -8,11 +8,11 @@ import {
createEmitAndSemanticDiagnosticsBuilderProgram, createGetCanonicalFileName, createResolutionCache,
CreateSourceFileOptions, createWatchCompilerHostOfConfigFile, createWatchCompilerHostOfFilesAndCompilerOptions,
createWatchFactory, Debug, Diagnostic, DiagnosticMessage, DiagnosticReporter, Diagnostics, DirectoryStructureHost,
DirectoryWatcherCallback, EmitAndSemanticDiagnosticsBuilderProgram, ESMap, ExtendedConfigCacheEntry,
DirectoryWatcherCallback, EmitAndSemanticDiagnosticsBuilderProgram, ExtendedConfigCacheEntry,
FileExtensionInfo, FileReference, FileWatcher, FileWatcherCallback, FileWatcherEventKind, getBuildInfo,
getConfigFileParsingDiagnostics, getDirectoryPath, getEntries, getFileNamesFromConfigSpecs, getNewLineCharacter,
getNormalizedAbsolutePath, getParsedCommandLineOfConfigFile, getTsBuildInfoEmitOutputFilePath,
HasInvalidatedResolutions, isArray, isIgnoredFileFromWildCardWatching, isProgramUptoDate, Map, MapLike, maybeBind,
HasInvalidatedResolutions, isArray, isIgnoredFileFromWildCardWatching, isProgramUptoDate, MapLike, maybeBind,
ModuleResolutionCache, ModuleResolutionInfo, noop, noopFileWatcher, parseConfigHostFromCompilerHostLike,
ParsedCommandLine, Path, perfLogger, PollingInterval, ProjectReference, ResolutionCacheHost, ResolvedModule,
ResolvedProjectReference, ResolvedTypeReferenceDirective, returnFalse, returnTrue, ScriptTarget,
@@ -213,7 +213,7 @@ export interface WatchCompilerHostOfConfigFile<T extends BuilderProgram> extends
*/
export interface WatchCompilerHostOfConfigFile<T extends BuilderProgram> extends WatchCompilerHost<T> {
configFileParsingResult?: ParsedCommandLine;
extendedConfigCache?: Map<ExtendedConfigCacheEntry>;
extendedConfigCache?: Map<string, ExtendedConfigCacheEntry>;
}
export interface Watch<T> {
@@ -281,7 +281,7 @@ interface ParsedConfig {
/** File watcher of the config file */
watcher?: FileWatcher;
/** Wild card directories watched from this config file */
watchedDirectories?: Map<WildcardDirectoryWatcher>;
watchedDirectories?: Map<string, WildcardDirectoryWatcher>;
/** Reload to be done for this config file */
reloadLevel?: ConfigFileProgramReloadLevel.Partial | ConfigFileProgramReloadLevel.Full;
}
@@ -310,12 +310,12 @@ export function createWatchProgram<T extends BuilderProgram>(host: WatchCompiler
let builderProgram: T;
let reloadLevel: ConfigFileProgramReloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
let missingFilesMap: ESMap<Path, FileWatcher>; // Map of file watchers for the missing files
let watchedWildcardDirectories: ESMap<string, WildcardDirectoryWatcher>; // map of watchers for the wild card directories in the config file
let missingFilesMap: Map<Path, FileWatcher>; // Map of file watchers for the missing files
let watchedWildcardDirectories: Map<string, WildcardDirectoryWatcher>; // map of watchers for the wild card directories in the config file
let timerToUpdateProgram: any; // timer callback to recompile the program
let timerToInvalidateFailedLookupResolutions: any; // timer callback to invalidate resolutions for changes in failed lookup locations
let parsedConfigs: ESMap<Path, ParsedConfig> | undefined; // Parsed commandline and watching cached for referenced projects
let sharedExtendedConfigFileWatchers: ESMap<Path, SharedExtendedConfigFileWatcher<Path>>; // Map of file watchers for extended files, shared between different referenced projects
let parsedConfigs: Map<Path, ParsedConfig> | undefined; // Parsed commandline and watching cached for referenced projects
let sharedExtendedConfigFileWatchers: Map<Path, SharedExtendedConfigFileWatcher<Path>>; // Map of file watchers for extended files, shared between different referenced projects
let extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation
let reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created
+10 -10
View File
@@ -2,12 +2,12 @@ import * as ts from "./_namespaces/ts";
import {
arrayToMap, binarySearch, BuilderProgram, closeFileWatcher, compareStringsCaseSensitive, CompilerOptions,
createGetCanonicalFileName, Debug, DirectoryWatcherCallback, emptyArray, emptyFileSystemEntries,
ensureTrailingDirectorySeparator, ESMap, ExtendedConfigCacheEntry, Extension, FileExtensionInfo,
ensureTrailingDirectorySeparator, ExtendedConfigCacheEntry, Extension, FileExtensionInfo,
fileExtensionIsOneOf, FileSystemEntries, FileWatcher, FileWatcherCallback, FileWatcherEventKind, find,
getBaseFileName, getDirectoryPath, getNormalizedAbsolutePath, hasExtension, identity, insertSorted, isArray,
isDeclarationFileName, isExcludedFile, isSupportedSourceFileName, map, Map, matchesExclude, matchFiles, mutateMap,
isDeclarationFileName, isExcludedFile, isSupportedSourceFileName, map, matchesExclude, matchFiles, mutateMap,
noop, normalizePath, outFile, Path, PollingInterval, Program, removeFileExtension, removeIgnoredPath,
returnNoopFileWatcher, returnTrue, Set, setSysLog, SortedArray, SortedReadonlyArray, supportedJSExtensionsFlat,
returnNoopFileWatcher, returnTrue, setSysLog, SortedArray, SortedReadonlyArray, supportedJSExtensionsFlat,
timestamp, WatchDirectoryFlags, WatchFileKind, WatchOptions,
} from "./_namespaces/ts";
@@ -342,7 +342,7 @@ export interface SharedExtendedConfigFileWatcher<T> extends FileWatcher {
export function updateSharedExtendedConfigFileWatcher<T>(
projectPath: T,
options: CompilerOptions | undefined,
extendedConfigFilesMap: ESMap<Path, SharedExtendedConfigFileWatcher<T>>,
extendedConfigFilesMap: Map<Path, SharedExtendedConfigFileWatcher<T>>,
createExtendedConfigFileWatch: (extendedConfigPath: string, extendedConfigFilePath: Path) => FileWatcher,
toPath: (fileName: string) => Path,
) {
@@ -383,7 +383,7 @@ export function updateSharedExtendedConfigFileWatcher<T>(
*/
export function clearSharedExtendedConfigFileWatcher<T>(
projectPath: T,
extendedConfigFilesMap: ESMap<Path, SharedExtendedConfigFileWatcher<T>>,
extendedConfigFilesMap: Map<Path, SharedExtendedConfigFileWatcher<T>>,
) {
extendedConfigFilesMap.forEach(watcher => {
if (watcher.projects.delete(projectPath)) watcher.close();
@@ -396,7 +396,7 @@ export function clearSharedExtendedConfigFileWatcher<T>(
* @internal
*/
export function cleanExtendedConfigCache(
extendedConfigCache: ESMap<string, ExtendedConfigCacheEntry>,
extendedConfigCache: Map<string, ExtendedConfigCacheEntry>,
extendedConfigFilePath: Path,
toPath: (fileName: string) => Path,
) {
@@ -415,7 +415,7 @@ export function cleanExtendedConfigCache(
*/
export function updatePackageJsonWatch(
lookups: readonly (readonly [Path, object | boolean])[],
packageJsonWatches: ESMap<Path, FileWatcher>,
packageJsonWatches: Map<Path, FileWatcher>,
createPackageJsonWatch: (packageJsonPath: Path, data: object | boolean) => FileWatcher,
) {
const newMap = new Map(lookups);
@@ -436,7 +436,7 @@ export function updatePackageJsonWatch(
*/
export function updateMissingFilePathsWatch(
program: Program,
missingFileWatches: ESMap<Path, FileWatcher>,
missingFileWatches: Map<Path, FileWatcher>,
createMissingFileWatch: (missingFilePath: Path) => FileWatcher,
) {
const missingFilePaths = program.getMissingFilePaths();
@@ -471,8 +471,8 @@ export interface WildcardDirectoryWatcher {
* @internal
*/
export function updateWatchingWildcardDirectories(
existingWatchedForWildcards: ESMap<string, WildcardDirectoryWatcher>,
wildcardDirectories: ESMap<string, WatchDirectoryFlags>,
existingWatchedForWildcards: Map<string, WildcardDirectoryWatcher>,
wildcardDirectories: Map<string, WatchDirectoryFlags>,
watchDirectory: (directory: string, flags: WatchDirectoryFlags) => FileWatcher
) {
mutateMap(
@@ -1,24 +0,0 @@
// DEPRECATION: Renamed `Map` and `ReadonlyMap` interfaces
// DEPRECATION PLAN:
// - soft: 4.0
// - remove: TBD (will remove for at least one release before replacing with `ESMap`/`ReadonlyESMap`)
// - replace: TBD (will eventually replace with `ESMap`/`ReadonlyESMap`)
declare module "../../compiler/corePublic" {
// Module transform: converted from interface augmentation
/**
* @deprecated Use `ts.ReadonlyESMap<K, V>` instead.
*/
export interface ReadonlyMap<T> extends ReadonlyESMap<string, T> {
}
}
declare module "../../compiler/corePublic" {
// Module transform: converted from interface augmentation
/**
* @deprecated Use `ts.ESMap<K, V>` instead.
*/
export interface Map<T> extends ESMap<string, T> {
}
}
export { };
-1
View File
@@ -4,7 +4,6 @@ export * from "../../compiler/_namespaces/ts";
export * from "../deprecations";
export * from "../4.0/nodeFactoryTopLevelExports";
export * from "../4.0/renamedNodeTests";
export * from "../4.0/renamedMapInterfaces";
export * from "../4.2/renamedNodeTests";
export * from "../4.2/abstractConstructorTypes";
export * from "../4.6/importTypeAssertions";
+8 -8
View File
@@ -8,11 +8,11 @@ import {
createSolutionBuilderWithWatchHost, createWatchCompilerHostOfConfigFile,
createWatchCompilerHostOfFilesAndCompilerOptions, createWatchProgram, Debug, Diagnostic, DiagnosticMessage,
DiagnosticReporter, Diagnostics, dumpTracingLegend, EmitAndSemanticDiagnosticsBuilderProgram,
emitFilesAndReportErrorsAndGetExitStatus, ESMap, ExitStatus, ExtendedConfigCacheEntry, Extension, fileExtensionIs,
emitFilesAndReportErrorsAndGetExitStatus, ExitStatus, ExtendedConfigCacheEntry, Extension, fileExtensionIs,
fileExtensionIsOneOf, filter, findConfigFile, forEach, formatMessage, generateTSConfig,
getBuildOrderFromAnyBuildOrder, getCompilerOptionsDiffValue, getConfigFileParsingDiagnostics, getDiagnosticText,
getEntries, getErrorSummaryText, getLineStarts, getNormalizedAbsolutePath, isIncrementalCompilation, isWatchSet,
Map, normalizePath, optionDeclarations, optionsForBuild, optionsForWatch, padLeft, padRight, parseBuildCommand,
normalizePath, optionDeclarations, optionsForBuild, optionsForWatch, padLeft, padRight, parseBuildCommand,
parseCommandLine, parseConfigFileWithSystem, ParsedCommandLine, Program, reduceLeftIterator, ReportEmitErrorSummary,
SolutionBuilder, SolutionBuilderHostBase, sort, SourceFile, startsWith, startTracing, stringContains,
supportedJSExtensionsFlat, supportedTSExtensionsFlat, sys, System, toPath, tracing, validateLocaleAndSetLanguage,
@@ -32,7 +32,7 @@ export enum StatisticType {
memory,
}
function countLines(program: Program): Map<number> {
function countLines(program: Program): Map<string, number> {
const counts = getCountsMap();
forEach(program.getSourceFiles(), file => {
const key = getCountKey(program, file);
@@ -278,13 +278,13 @@ function generateOptionOutput(sys: System, option: CommandLineOption, rightAlign
}
function getValueCandidate(option: CommandLineOption): ValueCandidate | undefined {
// option.type might be "string" | "number" | "boolean" | "object" | "list" | ESMap<string, number | string>
// option.type might be "string" | "number" | "boolean" | "object" | "list" | Map<string, number | string>
// string -- any of: string
// number -- any of: number
// boolean -- any of: boolean
// object -- null
// list -- one or more: , content depends on `option.element.type`, the same as others
// ESMap<string, number | string> -- any of: key1, key2, ....
// Map<string, number | string> -- any of: key1, key2, ....
if (option.type === "object") {
return undefined;
}
@@ -323,7 +323,7 @@ function generateOptionOutput(sys: System, option: CommandLineOption, rightAlign
possibleValues = "";
break;
default:
// ESMap<string, number | string>
// Map<string, number | string>
// Group synonyms: es6/es2015
const inverted: { [value: string]: string[] } = {};
option.type.forEach((value, name) => {
@@ -924,7 +924,7 @@ function createWatchOfConfigFile(
configParseResult: ParsedCommandLine,
optionsToExtend: CompilerOptions,
watchOptionsToExtend: WatchOptions | undefined,
extendedConfigCache: Map<ExtendedConfigCacheEntry>,
extendedConfigCache: Map<string, ExtendedConfigCacheEntry>,
) {
const watchCompilerHost = createWatchCompilerHostOfConfigFile({
configFileName: configParseResult.options.configFilePath!,
@@ -974,7 +974,7 @@ function enableSolutionPerformance(system: System, options: BuildOptions) {
}
function createSolutionPerfomrance(): SolutionPerformance {
let statistics: ESMap<string, Statistic> | undefined;
let statistics: Map<string, Statistic> | undefined;
return {
addAggregateStatistic,
forEachAggregateStatistics: forEachAggreateStatistics,
@@ -1,3 +0,0 @@
/* Generated file to emulate the ts.TestFSWithWatch namespace. */
export * from "../virtualFileSystemWithWatch";
+1 -3
View File
@@ -8,6 +8,4 @@ export * from "../../typingsInstallerCore/_namespaces/ts";
export * from "../../deprecatedCompat/_namespaces/ts";
export * from "../harnessGlobals";
import * as server from "./ts.server";
export { server };
import * as TestFSWithWatch from "./ts.TestFSWithWatch";
export { TestFSWithWatch };
export { server };
+2 -2
View File
@@ -6,9 +6,9 @@ import {
DiagnosticWithLocation, DocCommentTemplateOptions, DocumentHighlights, DocumentSpan, EditorOptions, EmitOutput,
FileTextChanges, firstDefined, FormatCodeOptions, FormatCodeSettings, getSnapshotText, identity,
ImplementationLocation, InlayHint, InlayHintKind, isString, JSDocTagInfo, LanguageService, LanguageServiceHost, map,
Map, mapOneOrMany, NavigateToItem, NavigationBarItem, NavigationTree, notImplemented, OrganizeImportsArgs,
mapOneOrMany, NavigateToItem, NavigationBarItem, NavigationTree, notImplemented, OrganizeImportsArgs,
OutliningSpan, PatternMatchKind, Program, QuickInfo, RefactorEditInfo, ReferencedSymbol, ReferenceEntry, RenameInfo,
RenameInfoFailure, RenameInfoSuccess, RenameLocation, ScriptElementKind, SemanticClassificationFormat, Set,
RenameInfoFailure, RenameInfoSuccess, RenameLocation, ScriptElementKind, SemanticClassificationFormat,
SignatureHelpItem, SignatureHelpItems, SourceFile, Symbol, TextChange, TextInsertion, textPart, TextRange, TextSpan,
TodoComment, TodoCommentDescriptor, UserPreferences,
} from "./_namespaces/ts";
+1 -1
View File
@@ -72,7 +72,7 @@ abstract class Loader<TModule> {
protected readonly fs: vfs.FileSystem;
protected readonly globals: Record<string, any>;
private moduleCache = new ts.Map<string, TModule>();
private moduleCache = new Map<string, TModule>();
constructor(fs: vfs.FileSystem, globals: Record<string, any>) {
this.fs = fs;
+13 -13
View File
@@ -36,7 +36,7 @@ interface FourSlashData {
symlinks: vfs.FileSet | undefined;
// A mapping from marker names to name/position pairs
markerPositions: ts.ESMap<string, Marker>;
markerPositions: Map<string, Marker>;
markers: Marker[];
@@ -184,7 +184,7 @@ export class TestState {
public formatCodeSettings: ts.FormatCodeSettings;
private inputFiles = new ts.Map<string, string>(); // Map between inputFile's fileName and its content for easily looking up when resolving references
private inputFiles = new Map<string, string>(); // Map between inputFile's fileName and its content for easily looking up when resolving references
private static getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[] | undefined) {
let result = "";
@@ -911,7 +911,7 @@ export class TestState {
"Expected 'optionalReplacementSpan' properties to match");
}
const nameToEntries = new ts.Map<string, ts.CompletionEntry[]>();
const nameToEntries = new Map<string, ts.CompletionEntry[]>();
for (const entry of actualCompletions.entries) {
const entries = nameToEntries.get(entry.name);
if (!entries) {
@@ -1126,7 +1126,7 @@ export class TestState {
}
public setTypesRegistry(map: ts.MapLike<void>): void {
this.languageServiceAdapterHost.typesRegistry = new ts.Map(ts.getEntries(map));
this.languageServiceAdapterHost.typesRegistry = new Map(ts.getEntries(map));
}
public verifyTypeOfSymbolAtLocation(range: Range, symbol: ts.Symbol, expected: string): void {
@@ -2522,7 +2522,7 @@ export class TestState {
return this.getRanges().filter(r => r.fileName === fileName);
}
public rangesByText(): ts.ESMap<string, Range[]> {
public rangesByText(): Map<string, Range[]> {
if (this.testData.rangesByText) return this.testData.rangesByText;
const result = ts.createMultiMap<Range>();
this.testData.rangesByText = result;
@@ -3161,7 +3161,7 @@ export class TestState {
public verifyBraceCompletionAtPosition(negative: boolean, openingBrace: string) {
const openBraceMap = new ts.Map(ts.getEntries<ts.CharacterCodes>({
const openBraceMap = new Map(ts.getEntries<ts.CharacterCodes>({
"(": ts.CharacterCodes.openParen,
"{": ts.CharacterCodes.openBrace,
"[": ts.CharacterCodes.openBracket,
@@ -3710,7 +3710,7 @@ export class TestState {
return text;
}
private formatCallHierarchyItem(file: FourSlashFile, callHierarchyItem: ts.CallHierarchyItem, direction: CallHierarchyItemDirection, seen: ts.ESMap<string, boolean>, prefix: string, trailingPrefix: string = prefix) {
private formatCallHierarchyItem(file: FourSlashFile, callHierarchyItem: ts.CallHierarchyItem, direction: CallHierarchyItemDirection, seen: Map<string, boolean>, prefix: string, trailingPrefix: string = prefix) {
const key = `${callHierarchyItem.file}|${JSON.stringify(callHierarchyItem.span)}|${direction}`;
const alreadySeen = seen.has(key);
seen.set(key, true);
@@ -3799,7 +3799,7 @@ export class TestState {
let text = "";
if (callHierarchyItem) {
const file = this.findFile(callHierarchyItem.file);
text += this.formatCallHierarchyItem(file, callHierarchyItem, CallHierarchyItemDirection.Root, new ts.Map(), "");
text += this.formatCallHierarchyItem(file, callHierarchyItem, CallHierarchyItemDirection.Root, new Map(), "");
}
return text;
}
@@ -4144,7 +4144,7 @@ function parseTestData(basePath: string, contents: string, fileName: string): Fo
const lines = contents.split("\n");
let i = 0;
const markerPositions = new ts.Map<string, Marker>();
const markerPositions = new Map<string, Marker>();
const markers: Marker[] = [];
const ranges: Range[] = [];
@@ -4283,7 +4283,7 @@ function reportError(fileName: string, line: number, col: number, message: strin
throw new Error(errorMessage);
}
function recordObjectMarker(fileName: string, location: LocationInformation, text: string, markerMap: ts.ESMap<string, Marker>, markers: Marker[]): Marker | undefined {
function recordObjectMarker(fileName: string, location: LocationInformation, text: string, markerMap: Map<string, Marker>, markers: Marker[]): Marker | undefined {
let markerValue: any;
try {
// Attempt to parse the marker value as JSON
@@ -4314,7 +4314,7 @@ function recordObjectMarker(fileName: string, location: LocationInformation, tex
return marker;
}
function recordMarker(fileName: string, location: LocationInformation, name: string, markerMap: ts.ESMap<string, Marker>, markers: Marker[]): Marker | undefined {
function recordMarker(fileName: string, location: LocationInformation, name: string, markerMap: Map<string, Marker>, markers: Marker[]): Marker | undefined {
const marker: Marker = {
fileName,
position: location.position
@@ -4333,7 +4333,7 @@ function recordMarker(fileName: string, location: LocationInformation, name: str
}
}
function parseFileContent(content: string, fileName: string, markerMap: ts.ESMap<string, Marker>, markers: Marker[], ranges: Range[]): FourSlashFile {
function parseFileContent(content: string, fileName: string, markerMap: Map<string, Marker>, markers: Marker[], ranges: Range[]): FourSlashFile {
content = chompLeadingSpace(content);
// Any slash-star comment with a character not in this string is not a marker.
@@ -4533,7 +4533,7 @@ function stringify(data: any, replacer?: (key: string, value: any) => any): stri
/** Collects an array of unique outputs. */
function unique<T>(inputs: readonly T[], getOutput: (t: T) => string): string[] {
const set = new ts.Map<string, true>();
const set = new Map<string, true>();
for (const input of inputs) {
const out = getOutput(input);
set.set(out, true);
+1 -1
View File
@@ -33,7 +33,7 @@ export class Test {
return this.ranges().map(r => ts.createTextSpan(r.pos, r.end - r.pos));
}
public rangesByText(): ts.ESMap<string, FourSlash.Range[]> {
public rangesByText(): Map<string, FourSlash.Range[]> {
return this.state.rangesByText();
}
+12 -12
View File
@@ -257,7 +257,7 @@ export namespace Compiler {
export const es2015DefaultLibFileName = "lib.es2015.d.ts";
// Cache of lib files from "built/local"
let libFileNameSourceFileMap: ts.ESMap<string, ts.SourceFile> | undefined;
let libFileNameSourceFileMap: Map<string, ts.SourceFile> | undefined;
export function getDefaultLibrarySourceFile(fileName = defaultLibFileName): ts.SourceFile | undefined {
if (!isDefaultLibraryFile(fileName)) {
@@ -265,7 +265,7 @@ export namespace Compiler {
}
if (!libFileNameSourceFileMap) {
libFileNameSourceFileMap = new ts.Map(ts.getEntries({
libFileNameSourceFileMap = new Map(ts.getEntries({
[defaultLibFileName]: createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.es5.d.ts")!, /*languageVersion*/ ts.ScriptTarget.Latest)
}));
}
@@ -327,10 +327,10 @@ export namespace Compiler {
{ name: "fullEmitPaths", type: "boolean", defaultValueDescription: false },
];
let optionsIndex: ts.ESMap<string, ts.CommandLineOption>;
let optionsIndex: Map<string, ts.CommandLineOption>;
function getCommandLineOption(name: string): ts.CommandLineOption | undefined {
if (!optionsIndex) {
optionsIndex = new ts.Map<string, ts.CommandLineOption>();
optionsIndex = new Map<string, ts.CommandLineOption>();
const optionDeclarations = harnessOptionDeclarations.concat(ts.optionDeclarations);
for (const option of optionDeclarations) {
optionsIndex.set(option.name.toLowerCase(), option);
@@ -609,7 +609,7 @@ export namespace Compiler {
errorsReported = 0;
// 'merge' the lines of each input file with any errors associated with it
const dupeCase = new ts.Map<string, number>();
const dupeCase = new Map<string, number>();
for (const inputFile of inputFiles.filter(f => f.content !== undefined)) {
// Filter down to the errors in the file
const fileErrors = diagnostics.filter((e): e is ts.DiagnosticWithLocation => {
@@ -789,7 +789,7 @@ export namespace Compiler {
if (skipBaseline) {
return;
}
const dupeCase = new ts.Map<string, number>();
const dupeCase = new Map<string, number>();
for (const file of allFiles) {
const { unitName } = file;
@@ -953,7 +953,7 @@ export namespace Compiler {
// Collect, test, and sort the fileNames
const files = Array.from(outputFiles);
files.slice().sort((a, b) => ts.compareStringsCaseSensitive(cleanName(a.file), cleanName(b.file)));
const dupeCase = new ts.Map<string, number>();
const dupeCase = new Map<string, number>();
// Yield them
for (const outputFile of files) {
yield [checkDuplicatedFileName(outputFile.file, dupeCase), "/*====== " + outputFile.file + " ======*/\r\n" + Utils.removeByteOrderMark(outputFile.text)];
@@ -965,7 +965,7 @@ export namespace Compiler {
}
}
function checkDuplicatedFileName(resultName: string, dupeCase: ts.ESMap<string, number>): string {
function checkDuplicatedFileName(resultName: string, dupeCase: Map<string, number>): string {
resultName = sanitizeTestFilePath(resultName);
if (dupeCase.has(resultName)) {
// A different baseline filename should be manufactured if the names differ only in case, for windows compat
@@ -1073,16 +1073,16 @@ function computeFileBasedTestConfigurationVariations(configurations: FileBasedTe
}
}
let booleanVaryByStarSettingValues: ts.ESMap<string, string | number> | undefined;
let booleanVaryByStarSettingValues: Map<string, string | number> | undefined;
function getVaryByStarSettingValues(varyBy: string): ts.ReadonlyESMap<string, string | number> | undefined {
function getVaryByStarSettingValues(varyBy: string): ReadonlyMap<string, string | number> | undefined {
const option = ts.forEach(ts.optionDeclarations, decl => ts.equateStringsCaseInsensitive(decl.name, varyBy) ? decl : undefined);
if (option) {
if (typeof option.type === "object") {
return option.type;
}
if (option.type === "boolean") {
return booleanVaryByStarSettingValues || (booleanVaryByStarSettingValues = new ts.Map(ts.getEntries({
return booleanVaryByStarSettingValues || (booleanVaryByStarSettingValues = new Map(ts.getEntries({
true: 1,
false: 0
})));
@@ -1420,7 +1420,7 @@ export namespace Baseline {
export function runMultifileBaseline(relativeFileBase: string, extension: string, generateContent: () => IterableIterator<[string, string, number]> | IterableIterator<[string, string]> | null, opts?: BaselineOptions, referencedExtensions?: string[]): void {
const gen = generateContent();
const writtenFiles = new ts.Map<string, true>();
const writtenFiles = new Map<string, true>();
const errors: Error[] = [];
// eslint-disable-next-line no-null/no-null
+2 -2
View File
@@ -132,7 +132,7 @@ export interface LanguageServiceAdapter {
export abstract class LanguageServiceAdapterHost {
public readonly sys = new fakes.System(new vfs.FileSystem(/*ignoreCase*/ true, { cwd: virtualFileSystemRoot }));
public typesRegistry: ts.ESMap<string, void> | undefined;
public typesRegistry: Map<string, void> | undefined;
private scriptInfos: collections.SortedMap<string, ScriptInfo>;
constructor(protected cancellationToken = DefaultHostCancellationToken.instance,
@@ -639,7 +639,7 @@ class LanguageServiceShimProxy implements ts.LanguageService {
getAutoImportProvider(): ts.Program | undefined {
throw new Error("Program can not be marshaled across the shim layer.");
}
updateIsDefinitionOfReferencedSymbols(_referencedSymbols: readonly ts.ReferencedSymbol[], _knownSymbolSpans: ts.Set<ts.DocumentSpan>): boolean {
updateIsDefinitionOfReferencedSymbols(_referencedSymbols: readonly ts.ReferencedSymbol[], _knownSymbolSpans: Set<ts.DocumentSpan>): boolean {
return ts.notImplemented();
}
getNonBoundSourceFile(): ts.SourceFile {
+1 -1
View File
@@ -54,7 +54,7 @@ export function readTestFile(path: string) {
}
export function memoize<T extends ts.AnyFunction>(f: T, memoKey: (...anything: any[]) => string): T {
const cache = new ts.Map<string, any>();
const cache = new Map<string, any>();
return (function (this: any, ...args: any[]) {
const key = memoKey(...args);
+1 -1
View File
@@ -328,7 +328,7 @@ export function getSourceMapRecord(sourceMapDataList: readonly ts.SourceMapEmitR
export function getSourceMapRecordWithSystem(sys: ts.System, sourceMapFile: string) {
const sourceMapRecorder = new Compiler.WriterAggregator();
let prevSourceFile: documents.TextDocument | undefined;
const files = new ts.Map<string, documents.TextDocument>();
const files = new Map<string, documents.TextDocument>();
const sourceMap = ts.tryParseRawSourceMap(sys.readFile(sourceMapFile, "utf8")!);
if (sourceMap) {
const mapDirectory = ts.getDirectoryPath(sourceMapFile);
-4
View File
@@ -3,10 +3,6 @@
"compilerOptions": {
"types": [
"node", "mocha", "chai"
],
"lib": [
"es6",
"scripthost"
]
},
"references": [
+4 -2
View File
@@ -42,6 +42,8 @@ export interface DiffOptions {
baseIsNotShadowRoot?: boolean;
}
export const timeIncrements = 1000;
/**
* Represents a virtual POSIX-like file system.
*/
@@ -65,7 +67,7 @@ export class FileSystem {
private _dirStack: string[] | undefined;
constructor(ignoreCase: boolean, options: FileSystemOptions = {}) {
const { time = ts.TestFSWithWatch.timeIncrements, files, meta } = options;
const { time = timeIncrements, files, meta } = options;
this.ignoreCase = ignoreCase;
this.stringComparer = this.ignoreCase ? vpath.compareCaseInsensitive : vpath.compareCaseSensitive;
this._time = time;
@@ -178,7 +180,7 @@ export class FileSystem {
this._time = value;
}
else if (!this.isReadonly) {
this._time += ts.TestFSWithWatch.timeIncrements;
this._time += timeIncrements;
}
return this._time;
}
+6 -6
View File
@@ -1,9 +1,9 @@
import {
CharacterCodes, combinePaths, compareStringsCaseSensitive, CompilerOptions, Debug, deduplicate,
equateStringsCaseSensitive, Extension, fileExtensionIs, flatMap, forEach, getBaseFileName, getDirectoryPath,
getEntries, getNormalizedAbsolutePath, getOwnKeys, getPathComponents, getProperty, hasJSFileExtension, Map,
mapDefined, MapLike, normalizePath, Path, readConfigFile, ReadonlyESMap, removeFileExtension,
removeMinAndVersionNumbers, Set, some, TypeAcquisition, Version, versionMajorMinor,
getEntries, getNormalizedAbsolutePath, getOwnKeys, getPathComponents, getProperty, hasJSFileExtension,
mapDefined, MapLike, normalizePath, Path, readConfigFile, removeFileExtension,
removeMinAndVersionNumbers, some, TypeAcquisition, Version, versionMajorMinor,
} from "./_namespaces/ts";
/** @internal */
@@ -105,7 +105,7 @@ export function nonRelativeModuleNameForTypingCache(moduleName: string) {
*
* @internal
*/
export type SafeList = ReadonlyESMap<string, string>;
export type SafeList = ReadonlyMap<string, string>;
/** @internal */
export function loadSafeList(host: TypingResolutionHost, safeListPath: Path): SafeList {
@@ -139,10 +139,10 @@ export function discoverTypings(
fileNames: string[],
projectRootPath: Path,
safeList: SafeList,
packageNameToTypingLocation: ReadonlyESMap<string, CachedTyping>,
packageNameToTypingLocation: ReadonlyMap<string, CachedTyping>,
typeAcquisition: TypeAcquisition,
unresolvedImports: readonly string[],
typesRegistry: ReadonlyESMap<string, MapLike<string>>,
typesRegistry: ReadonlyMap<string, MapLike<string>>,
compilerOptions: CompilerOptions):
{ cachedTypingPaths: string[], newTypingNames: string[], filesToWatch: string[] } {
-4
View File
@@ -3,10 +3,6 @@
"compilerOptions": {
"types": [
"node"
],
"lib": [
"es6",
"scripthost"
]
},
"references": [
+2 -2
View File
@@ -85,7 +85,7 @@ interface PlaybackControl {
let recordLog: IoLog | undefined;
let replayLog: IoLog | undefined;
let replayFilesRead: ts.ESMap<string, IoLogFile> | undefined;
let replayFilesRead: Map<string, IoLogFile> | undefined;
let recordLogFileNameBase = "";
interface Memoized<T> {
@@ -219,7 +219,7 @@ export function initWrapper(...[wrapper, underlying]: [PlaybackSystem, ts.System
replayLog = log;
// Remove non-found files from the log (shouldn't really need them, but we still record them for diagnostic purposes)
replayLog.filesRead = replayLog.filesRead.filter(f => f.result!.contents !== undefined);
replayFilesRead = new ts.Map();
replayFilesRead = new Map();
for (const file of replayLog.filesRead) {
replayFilesRead.set(ts.normalizeSlashes(file.path).toLowerCase(), file);
}
-4
View File
@@ -2,10 +2,6 @@
"extends": "../tsconfig-base",
"compilerOptions": {
"types": [
],
"lib": [
"es6",
"scripthost"
]
},
"references": [
+49 -34
View File
@@ -15,20 +15,20 @@ import {
contains, containsPath, convertCompilerOptionsForTelemetry, convertEnableAutoDiscoveryToEnable, convertJsonOption,
createCachedDirectoryStructureHost, createDocumentRegistryInternal, createGetCanonicalFileName, createMultiMap,
Debug, Diagnostic, directorySeparator, DirectoryStructureHost, DocumentPosition, DocumentPositionMapper,
DocumentRegistry, DocumentRegistryBucketKeyWithMode, emptyOptions, ensureTrailingDirectorySeparator, ESMap,
DocumentRegistry, DocumentRegistryBucketKeyWithMode, emptyOptions, ensureTrailingDirectorySeparator,
ExtendedConfigCacheEntry, FileExtensionInfo, fileExtensionIs, FileWatcher, FileWatcherEventKind, find, flatMap,
forEach, forEachAncestorDirectory, forEachEntry, forEachKey, forEachResolvedProjectReference, FormatCodeSettings,
getAnyExtensionFromPath, getBaseFileName, getDefaultFormatCodeSettings, getDirectoryPath, getDocumentPositionMapper,
getEntries, getFileNamesFromConfigSpecs, getFileWatcherEventKind, getNormalizedAbsolutePath, getSnapshotText,
getWatchFactory, hasExtension, hasProperty, hasTSFileExtension, HostCancellationToken, identity,
IncompleteCompletionsCache, IndentStyle, isArray, isIgnoredFileFromWildCardWatching, isInsideNodeModules,
isJsonEqual, isNodeModulesDirectory, isRootedDiskPath, isString, Iterator, LanguageServiceMode, length, map, Map,
isJsonEqual, isNodeModulesDirectory, isRootedDiskPath, isString, LanguageServiceMode, length, map,
mapDefinedEntries, mapDefinedIterator, missingFileModifiedTime, MultiMap, noop, normalizePath, normalizeSlashes,
optionDeclarations, optionsForWatch, PackageJsonAutoImportPreference, ParsedCommandLine,
parseJsonSourceFileConfigFileContent, parseJsonText, parsePackageName, Path, PerformanceEvent, PluginImport,
PollingInterval, ProjectPackageJsonInfo, ProjectReference, ReadMapFile, ReadonlyCollection, removeFileExtension,
removeIgnoredPath, removeMinAndVersionNumbers, ResolvedProjectReference, resolveProjectReferencePath,
returnNoopFileWatcher, returnTrue, ScriptKind, Set, SharedExtendedConfigFileWatcher, some, SourceFile, SourceFileLike, startsWith,
returnNoopFileWatcher, returnTrue, ScriptKind, SharedExtendedConfigFileWatcher, some, SourceFile, SourceFileLike, startsWith,
Ternary, TextChange, toFileNameLowerCase, toPath, tracing, tryAddToSet, tryReadFile, TsConfigSourceFile,
TypeAcquisition, typeAcquisitionDeclarations, unorderedRemoveItem, updateSharedExtendedConfigFileWatcher,
updateWatchingWildcardDirectories, UserPreferences, version, WatchDirectoryFlags, WatchFactory, WatchLogLevel,
@@ -193,11 +193,11 @@ export interface SafeList {
[name: string]: { match: RegExp, exclude?: (string | number)[][], types?: string[] };
}
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions: CommandLineOption[]): ESMap<string, ESMap<string, number>> {
const map = new Map<string, ESMap<string, number>>();
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions: CommandLineOption[]): Map<string, Map<string, number>> {
const map = new Map<string, Map<string, number>>();
for (const option of commandLineOptions) {
if (typeof option.type === "object") {
const optionMap = option.type as ESMap<string, number>;
const optionMap = option.type as Map<string, number>;
// verify that map contains only numbers
optionMap.forEach(value => {
Debug.assert(typeof value === "number");
@@ -413,7 +413,7 @@ export interface ConfigFileExistenceInfo {
* It is false when the open file that would still be impacted by existence of
* this config file but it is not the root of inferred project
*/
openFilesImpactedByConfigFile?: ESMap<Path, boolean>;
openFilesImpactedByConfigFile?: Map<Path, boolean>;
/**
* The file watcher watching the config file because there is open script info that is root of
* inferred project and will be impacted by change in the status of the config file
@@ -506,7 +506,7 @@ export function forEachResolvedProjectReferenceProject<T>(
): T | undefined {
const resolvedRefs = project.getCurrentProgram()?.getResolvedProjectReferences();
if (!resolvedRefs) return undefined;
let seenResolvedRefs: ESMap<string, ProjectReferenceProjectLoadKind> | undefined;
let seenResolvedRefs: Map<string, ProjectReferenceProjectLoadKind> | undefined;
const possibleDefaultRef = fileName ? project.getResolvedProjectReferenceToRedirect(fileName) : undefined;
if (possibleDefaultRef) {
// Try to find the name of the file directly through resolved project references
@@ -564,7 +564,7 @@ function forEachResolvedProjectReferenceProjectWorker<T>(
cb: (resolvedRef: ResolvedProjectReference, loadKind: ProjectReferenceProjectLoadKind) => T | undefined,
projectReferenceProjectLoadKind: ProjectReferenceProjectLoadKind,
projectService: ProjectService,
seenResolvedRefs: ESMap<string, ProjectReferenceProjectLoadKind> | undefined,
seenResolvedRefs: Map<string, ProjectReferenceProjectLoadKind> | undefined,
): T | undefined {
const loadKind = parentOptions.disableReferencedProjectLoad ? ProjectReferenceProjectLoadKind.Find : projectReferenceProjectLoadKind;
return forEach(resolvedProjectReferences, ref => {
@@ -693,9 +693,9 @@ export interface ParsedConfig{
* - true if project is watching config file as well as wild cards
* - false if just config file is watched
*/
projects: ESMap<NormalizedPath, boolean>;
projects: Map<NormalizedPath, boolean>;
parsedCommandLine?: ParsedCommandLine;
watchedDirectories?: Map<WildcardDirectoryWatcher>;
watchedDirectories?: Map<string, WildcardDirectoryWatcher>;
/**
* true if watchedDirectories need to be updated as per parsedCommandLine's updated watched directories
*/
@@ -718,8 +718,9 @@ export class ProjectService {
/**
* Container of all known scripts
*
* @internal
*/
/** @internal */
readonly filenameToScriptInfo = new Map<string, ScriptInfo>();
private readonly nodeModulesWatchers = new Map<string, NodeModulesWatcher>();
/**
@@ -733,8 +734,9 @@ export class ProjectService {
/**
* Map to the real path of the infos
*
* @internal
*/
/** @internal */
readonly realpathToScriptInfos: MultiMap<Path, ScriptInfo> | undefined;
/**
* maps external project file name to list of config files that were the part of this project
@@ -752,7 +754,7 @@ export class ProjectService {
/**
* projects specified by a tsconfig.json file
*/
readonly configuredProjects: Map<ConfiguredProject> = new Map<string, ConfiguredProject>();
readonly configuredProjects: Map<string, ConfiguredProject> = new Map<string, ConfiguredProject>();
/** @internal */
readonly newInferredProjectName = createProjectNameFactoryWithCounter(makeInferredProjectName);
/** @internal */
@@ -762,9 +764,9 @@ export class ProjectService {
/**
* Open files: with value being project root path, and key being Path of the file that is open
*/
readonly openFiles: Map<NormalizedPath | undefined> = new Map<Path, NormalizedPath | undefined>();
readonly openFiles: Map<string, NormalizedPath | undefined> = new Map<Path, NormalizedPath | undefined>();
/** @internal */
readonly configFileForOpenFiles: ESMap<Path, NormalizedPath | false> = new Map();
readonly configFileForOpenFiles: Map<Path, NormalizedPath | false> = new Map();
/**
* Map of open files that are opened without complete path but have projectRoot as current directory
*/
@@ -786,8 +788,11 @@ export class ProjectService {
* In this case the exists could be true/false based on config file is present or not
* - Or it is present if we have configured project open with config file at that location
* In this case the exists property is always true
*
*
* @internal
*/
/** @internal */ readonly configFileExistenceInfoCache = new Map<NormalizedPath, ConfigFileExistenceInfo>();
readonly configFileExistenceInfoCache = new Map<NormalizedPath, ConfigFileExistenceInfo>();
/** @internal */ readonly throttledOperations: ThrottledOperations;
private readonly hostConfiguration: HostConfiguration;
@@ -815,7 +820,7 @@ export class ProjectService {
public readonly globalPlugins: readonly string[];
public readonly pluginProbeLocations: readonly string[];
public readonly allowLocalPluginLoads: boolean;
private currentPluginConfigOverrides: ESMap<string, any> | undefined;
private currentPluginConfigOverrides: Map<string, any> | undefined;
public readonly typesMapLocation: string | undefined;
@@ -837,7 +842,7 @@ export class ProjectService {
/** @internal */
readonly packageJsonCache: PackageJsonCache;
/** @internal */
private packageJsonFilesMap: ESMap<Path, FileWatcher> | undefined;
private packageJsonFilesMap: Map<Path, FileWatcher> | undefined;
/** @internal */
private incompleteCompletionsCache: IncompleteCompletionsCache | undefined;
/** @internal */
@@ -846,7 +851,7 @@ export class ProjectService {
private performanceEventHandler?: PerformanceEventHandler;
private pendingPluginEnablements?: ESMap<Project, Promise<BeginEnablePluginResult>[]>;
private pendingPluginEnablements?: Map<Project, Promise<BeginEnablePluginResult>[]>;
private currentPluginEnablementPromise?: Promise<void>;
constructor(opts: ProjectServiceOptions) {
@@ -1344,8 +1349,9 @@ export class ProjectService {
/**
* This is to watch whenever files are added or removed to the wildcard directories
*
* @internal
*/
/** @internal */
private watchWildcardDirectory(directory: Path, flags: WatchDirectoryFlags, configFileName: NormalizedPath, config: ParsedConfig) {
return this.watchFactory.watchDirectory(
directory,
@@ -1701,7 +1707,7 @@ export class ProjectService {
// Cache the host value of file exists and add the info to map of open files impacted by this config file
const exists = this.host.fileExists(configFileName);
let openFilesImpactedByConfigFile: ESMap<Path, boolean> | undefined;
let openFilesImpactedByConfigFile: Map<Path, boolean> | undefined;
if (isOpenScriptInfo(info)) {
(openFilesImpactedByConfigFile ||= new Map()).set(info.path, false);
}
@@ -1774,8 +1780,9 @@ export class ProjectService {
/**
* Close the config file watcher in the cached ConfigFileExistenceInfo
* if there arent any open files that are root of inferred project and there is no parsed config held by any project
*
* @internal
*/
/** @internal */
private closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo: ConfigFileExistenceInfo) {
// Close the config file watcher if there are no more open files that are root of inferred project
// or if there are no projects that need to watch this config file existence info
@@ -1822,8 +1829,9 @@ export class ProjectService {
/**
* This is called by inferred project whenever script info is added as a root
*
* @internal
*/
/** @internal */
startWatchingConfigFilesForInferredProjectRoot(info: ScriptInfo) {
Debug.assert(info.isScriptOpen());
this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName) => {
@@ -1852,8 +1860,9 @@ export class ProjectService {
/**
* This is called by inferred project whenever root script info is removed from it
*
* @internal
*/
/** @internal */
stopWatchingConfigFilesForInferredProjectRoot(info: ScriptInfo) {
this.forEachConfigFileLocation(info, canonicalConfigFilePath => {
const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
@@ -2168,8 +2177,9 @@ export class ProjectService {
/**
* Read the config file of the project, and update the project root file names.
*
* @internal
*/
/** @internal */
private loadConfiguredProject(project: ConfiguredProject, reason: string) {
tracing?.push(tracing.Phase.Session, "loadConfiguredProject", { configFilePath: project.canonicalConfigFilePath });
this.sendProjectLoadingStartEvent(project, reason);
@@ -2434,8 +2444,9 @@ export class ProjectService {
/**
* Reload the file names from config file specs and update the project graph
*
* @internal
*/
/** @internal */
reloadFileNamesOfConfiguredProject(project: ConfiguredProject) {
const fileNames = this.reloadFileNamesOfParsedConfig(project.getConfigFilePath(), this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath)!.config!);
project.updateErrorOnNoInputFiles(fileNames);
@@ -2466,8 +2477,9 @@ export class ProjectService {
/**
* Read the config file of the project again by clearing the cache and update the project graph
*
* @internal
*/
/** @internal */
reloadConfiguredProject(project: ConfiguredProject, reason: string, isInitialLoad: boolean, clearSemanticCache: boolean) {
// At this point, there is no reason to not have configFile in the host
const host = project.getCachedDirectoryStructureHost();
@@ -2632,8 +2644,9 @@ export class ProjectService {
/**
* Returns the projects that contain script info through SymLink
* Note that this does not return projects in info.containingProjects
*
* @internal
*/
/** @internal */
getSymlinkedProjects(info: ScriptInfo): MultiMap<Path, Project> | undefined {
let projects: MultiMap<Path, Project> | undefined;
if (this.realpathToScriptInfos) {
@@ -3130,7 +3143,7 @@ export class ProjectService {
});
// Reload Projects
this.reloadConfiguredProjectForFiles(this.openFiles as ESMap<Path, NormalizedPath | undefined>, /*clearSemanticCache*/ true, /*delayReload*/ false, returnTrue, "User requested reload projects");
this.reloadConfiguredProjectForFiles(this.openFiles as Map<Path, NormalizedPath | undefined>, /*clearSemanticCache*/ true, /*delayReload*/ false, returnTrue, "User requested reload projects");
this.externalProjects.forEach(project => {
this.clearSemanticCache(project);
project.updateGraph();
@@ -3146,7 +3159,7 @@ export class ProjectService {
* If there is no existing project it just opens the configured project for the config file
* reloadForInfo provides a way to filter out files to reload configured project for
*/
private reloadConfiguredProjectForFiles<T>(openFiles: ESMap<Path, T> | undefined, clearSemanticCache: boolean, delayReload: boolean, shouldReloadProjectFor: (openFileValue: T) => boolean, reason: string) {
private reloadConfiguredProjectForFiles<T>(openFiles: Map<Path, T> | undefined, clearSemanticCache: boolean, delayReload: boolean, shouldReloadProjectFor: (openFileValue: T) => boolean, reason: string) {
const updatedProjects = new Map<string, true>();
const reloadChildProject = (child: ConfiguredProject) => {
if (!updatedProjects.has(child.canonicalConfigFilePath)) {
@@ -4111,7 +4124,7 @@ export class ProjectService {
}
/** @internal */
requestEnablePlugin(project: Project, pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map<any> | undefined) {
requestEnablePlugin(project: Project, pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map<string, any> | undefined) {
if (!this.host.importPlugin && !this.host.require) {
this.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
return;
@@ -4149,8 +4162,9 @@ export class ProjectService {
/**
* Waits for any ongoing plugin enablement requests to complete.
*
* @internal
*/
/** @internal */
async waitForPendingPlugins() {
while (this.currentPluginEnablementPromise) {
await this.currentPluginEnablementPromise;
@@ -4159,8 +4173,9 @@ export class ProjectService {
/**
* Starts enabling any requested plugins without waiting for the result.
*
* @internal
*/
/** @internal */
enableRequestedPlugins() {
if (this.pendingPluginEnablements) {
void this.enableRequestedPluginsAsync();
+3 -3
View File
@@ -1,5 +1,5 @@
import {
Debug, ESMap, FileWatcher, Map, ModulePath, ModuleSpecifierCache, ModuleSpecifierOptions, nodeModulesPathPart, Path,
Debug, FileWatcher, ModulePath, ModuleSpecifierCache, ModuleSpecifierOptions, nodeModulesPathPart, Path,
ResolvedModuleSpecifierInfo, UserPreferences,
} from "./_namespaces/ts";
@@ -10,8 +10,8 @@ export interface ModuleSpecifierResolutionCacheHost {
/** @internal */
export function createModuleSpecifierCache(host: ModuleSpecifierResolutionCacheHost): ModuleSpecifierCache {
let containedNodeModulesWatchers: ESMap<string, FileWatcher> | undefined;
let cache: ESMap<Path, ResolvedModuleSpecifierInfo> | undefined;
let containedNodeModulesWatchers: Map<string, FileWatcher> | undefined;
let cache: Map<Path, ResolvedModuleSpecifierInfo> | undefined;
let currentKey: string | undefined;
const result: ModuleSpecifierCache = {
get(fromFileName, toFileName, preferences, options) {
+1 -1
View File
@@ -1,5 +1,5 @@
import {
combinePaths, createPackageJsonInfo, Debug, forEachAncestorDirectory, getDirectoryPath, Map, Path,
combinePaths, createPackageJsonInfo, Debug, forEachAncestorDirectory, getDirectoryPath, Path,
ProjectPackageJsonInfo, Ternary, tryFileExists,
} from "./_namespaces/ts";
import { ProjectService } from "./_namespaces/ts.server";
+53 -37
View File
@@ -10,7 +10,7 @@ import {
changesAffectModuleResolution, clearMap, cloneCompilerOptions, closeFileWatcher, closeFileWatcherOf, combinePaths,
CompilerHost, CompilerOptions, concatenate, ConfigFileProgramReloadLevel, createCacheableExportInfoMap,
createLanguageService, createResolutionCache, createSymlinkCache, Debug, Diagnostic, DirectoryStructureHost,
DirectoryWatcherCallback, DocumentPositionMapper, DocumentRegistry, enumerateInsertsAndDeletes, ESMap, every,
DirectoryWatcherCallback, DocumentPositionMapper, DocumentRegistry, enumerateInsertsAndDeletes, every,
explainFiles, ExportInfoMap, Extension, fileExtensionIs, FileReference, FileWatcher, FileWatcherCallback,
FileWatcherEventKind, filter, firstDefined, flatMap, forEach, forEachEntry, forEachKey, generateDjb2Hash,
getAllowJSCompilerOption, getAutomaticTypeDirectiveNames, GetCanonicalFileName,
@@ -19,13 +19,13 @@ import {
getNormalizedAbsolutePath, getOrUpdate, getStringComparer, HasInvalidatedResolutions, HostCancellationToken,
inferredTypesContainingFile, InstallPackageOptions, IScriptSnapshot, isDeclarationFileName,
isExternalModuleNameRelative, isInsideNodeModules, JsTyping, LanguageService, LanguageServiceHost,
LanguageServiceMode, map, Map, mapDefined, maybeBind, ModuleKind, ModuleResolutionCache, ModuleResolutionHost,
LanguageServiceMode, map, mapDefined, maybeBind, ModuleKind, ModuleResolutionCache, ModuleResolutionHost,
ModuleResolutionInfo, noop, noopFileWatcher, normalizePath, normalizeSlashes, orderedRemoveItem, outFile,
PackageJsonAutoImportPreference, PackageJsonInfo, ParsedCommandLine, parsePackageName, Path, perfLogger,
PerformanceEvent, PluginImport, PollingInterval, Program, ProjectPackageJsonInfo, ProjectReference,
removeFileExtension, ResolutionCache, resolutionExtensionIsTSOrJson, ResolvedModuleFull,
ResolvedModuleWithFailedLookupLocations, ResolvedProjectReference, ResolvedTypeReferenceDirective,
resolvePackageNameToPackageJson, returnFalse, returnTrue, ScriptKind, Set, some, sort, sortAndDeduplicate,
resolvePackageNameToPackageJson, returnFalse, returnTrue, ScriptKind, some, sort, sortAndDeduplicate,
SortedReadonlyArray, SourceFile, SourceMapper, startsWith, stripQuotes, StructureIsReused, SymlinkCache,
ThrottledCancellationToken, timestamp, toPath, tracing, TypeAcquisition, TypeReferenceDirectiveResolutionInfo, updateErrorForNoInputFiles,
updateMissingFilePathsWatch, WatchDirectoryFlags, WatchOptions, WatchType,
@@ -136,7 +136,7 @@ export type PluginModuleFactory = (mod: { typescript: typeof ts }) => PluginModu
/** @internal */
export interface BeginEnablePluginResult {
pluginConfigEntry: PluginImport;
pluginConfigOverrides: Map<any> | undefined;
pluginConfigOverrides: Map<string, any> | undefined;
resolvedModule: PluginModuleFactory | undefined;
errorLogs: string[] | undefined;
}
@@ -156,7 +156,7 @@ interface GeneratedFileWatcher {
generatedFilePath: Path;
watcher: FileWatcher;
}
type GeneratedFileWatcherMap = GeneratedFileWatcher | ESMap<Path, GeneratedFileWatcher>;
type GeneratedFileWatcherMap = GeneratedFileWatcher | Map<Path, GeneratedFileWatcher>;
function isGeneratedFileWatcher(watch: GeneratedFileWatcherMap): watch is GeneratedFileWatcher {
return (watch as GeneratedFileWatcher).generatedFilePath !== undefined;
}
@@ -172,17 +172,18 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
private rootFilesMap = new Map<string, ProjectRootFile>();
private program: Program | undefined;
private externalFiles: SortedReadonlyArray<string> | undefined;
private missingFilesMap: ESMap<Path, FileWatcher> | undefined;
private missingFilesMap: Map<Path, FileWatcher> | undefined;
private generatedFilesMap: GeneratedFileWatcherMap | undefined;
/*@internal*/
/** @internal */
protected readonly plugins: PluginModuleWithName[] = [];
/** @internal */
/**
* This is map from files to unresolved imports in it
* Maop does not contain entries for files that do not have unresolved imports
* This helps in containing the set of files to invalidate
*
* @internal
*/
cachedUnresolvedImportsPerFile = new Map<Path, readonly string[]>();
@@ -218,7 +219,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
*/
private lastReportedFileNames: ESMap<string, boolean> | undefined;
private lastReportedFileNames: Map<string, boolean> | undefined;
/**
* Last version that was reported.
*/
@@ -998,7 +999,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
return this.getFileNames().map((fileName): protocol.FileWithProjectReferenceRedirectInfo => ({
fileName,
isSourceOfProjectReferenceRedirect: includeProjectReferenceRedirectInfo && this.isSourceOfProjectReferenceRedirect(fileName)
}));
}));
}
hasConfigFile(configFilePath: NormalizedPath) {
@@ -1281,7 +1282,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
watcher
)) {
closeFileWatcherOf(watcher);
(this.generatedFilesMap as ESMap<string, GeneratedFileWatcher>).delete(source);
(this.generatedFilesMap as Map<string, GeneratedFileWatcher>).delete(source);
}
});
}
@@ -1530,11 +1531,11 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
getChangesSinceVersion(lastKnownVersion?: number, includeProjectReferenceRedirectInfo?: boolean): ProjectFilesWithTSDiagnostics {
const includeProjectReferenceRedirectInfoIfRequested =
includeProjectReferenceRedirectInfo
? (files: ESMap<string, boolean>) => arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]): protocol.FileWithProjectReferenceRedirectInfo => ({
? (files: Map<string, boolean>) => arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]): protocol.FileWithProjectReferenceRedirectInfo => ({
fileName,
isSourceOfProjectReferenceRedirect
}))
: (files: ESMap<string, boolean>) => arrayFrom(files.keys());
: (files: Map<string, boolean>) => arrayFrom(files.keys());
// Update the graph only if initial configured project load is not pending
if (!this.isInitialLoadPending()) {
@@ -1569,8 +1570,8 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
info => info.isSourceOfProjectReferenceRedirect
);
const added: ESMap<string, boolean> = new Map<string, boolean>();
const removed: ESMap<string, boolean> = new Map<string, boolean>();
const added: Map<string, boolean> = new Map<string, boolean>();
const removed: Map<string, boolean> = new Map<string, boolean>();
const updated: string[] = updatedFileNames ? arrayFrom(updatedFileNames.keys()) : [];
const updatedRedirects: protocol.FileWithProjectReferenceRedirectInfo[] = [];
@@ -1579,7 +1580,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
if (!lastReportedFileNames.has(fileName)) {
added.set(fileName, isSourceOfProjectReferenceRedirect);
}
else if (includeProjectReferenceRedirectInfo && isSourceOfProjectReferenceRedirect !== lastReportedFileNames.get(fileName)){
else if (includeProjectReferenceRedirectInfo && isSourceOfProjectReferenceRedirect !== lastReportedFileNames.get(fileName)) {
updatedRedirects.push({
fileName,
isSourceOfProjectReferenceRedirect
@@ -1642,7 +1643,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
return !!this.program && this.program.isSourceOfProjectReferenceRedirect(fileName);
}
/*@internal*/
/** @internal */
protected getGlobalPluginSearchPaths() {
// Search any globally-specified probe paths, then our peer node_modules
return [
@@ -1652,7 +1653,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
];
}
protected enableGlobalPlugins(options: CompilerOptions, pluginConfigOverrides: Map<any> | undefined): void {
protected enableGlobalPlugins(options: CompilerOptions, pluginConfigOverrides: Map<string, any> | undefined): void {
if (!this.projectService.globalPlugins.length) return;
const host = this.projectService.host;
@@ -1679,9 +1680,10 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
/**
* Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin synchronously using 'require'.
*
* @internal
*/
/** @internal */
beginEnablePluginSync(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map<any> | undefined): BeginEnablePluginResult {
beginEnablePluginSync(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map<string, any> | undefined): BeginEnablePluginResult {
Debug.assertIsDefined(this.projectService.host.require);
let errorLogs: string[] | undefined;
@@ -1696,9 +1698,10 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
/**
* Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin asynchronously using dynamic `import`.
*
* @internal
*/
/** @internal */
async beginEnablePluginAsync(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map<any> | undefined): Promise<BeginEnablePluginResult> {
async beginEnablePluginAsync(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map<string, any> | undefined): Promise<BeginEnablePluginResult> {
Debug.assertIsDefined(this.projectService.host.importPlugin);
let errorLogs: string[] | undefined;
@@ -1719,8 +1722,9 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
/**
* Performs the remaining steps of enabling a plugin after its module has been instantiated.
*
* @internal
*/
/** @internal */
endEnablePlugin({ pluginConfigEntry, pluginConfigOverrides, resolvedModule, errorLogs }: BeginEnablePluginResult) {
if (resolvedModule) {
const configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name);
@@ -1739,7 +1743,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
}
protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map<any> | undefined): void {
protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map<string, any> | undefined): void {
this.projectService.requestEnablePlugin(this, pluginConfigEntry, searchPaths, pluginConfigOverrides);
}
@@ -1957,7 +1961,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
}
function getUnresolvedImports(program: Program, cachedUnresolvedImportsPerFile: ESMap<Path, readonly string[]>): SortedReadonlyArray<string> {
function getUnresolvedImports(program: Program, cachedUnresolvedImportsPerFile: Map<Path, readonly string[]>): SortedReadonlyArray<string> {
const sourceFiles = program.getSourceFiles();
tracing?.push(tracing.Phase.Session, "getUnresolvedImports", { count: sourceFiles.length });
const ambientModules = program.getTypeChecker().getAmbientModules().map(mod => stripQuotes(mod.getName()));
@@ -1966,7 +1970,7 @@ function getUnresolvedImports(program: Program, cachedUnresolvedImportsPerFile:
tracing?.pop();
return result;
}
function extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules: readonly string[], cachedUnresolvedImportsPerFile: ESMap<Path, readonly string[]>): readonly string[] {
function extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules: readonly string[], cachedUnresolvedImportsPerFile: Map<Path, readonly string[]>): readonly string[] {
return getOrUpdate(cachedUnresolvedImportsPerFile, file.path, () => {
if (!file.resolvedModules) return emptyArray;
let unresolvedImports: string[] | undefined;
@@ -2015,8 +2019,11 @@ export class InferredProject extends Project {
/** this is canonical project root path */
readonly projectRootPath: string | undefined;
/** @internal */
/** stored only if their is no projectRootPath and this isnt single inferred project */
/**
* stored only if their is no projectRootPath and this isnt single inferred project
*
* @internal
*/
readonly canonicalCurrentDirectory: string | undefined;
/** @internal */
@@ -2027,7 +2034,7 @@ export class InferredProject extends Project {
watchOptions: WatchOptions | undefined,
projectRootPath: NormalizedPath | undefined,
currentDirectory: string | undefined,
pluginConfigOverrides: ESMap<string, any> | undefined,
pluginConfigOverrides: Map<string, any> | undefined,
typeAcquisition: TypeAcquisition | undefined) {
super(projectService.newInferredProjectName(),
ProjectKind.Inferred,
@@ -2412,8 +2419,11 @@ export class ConfiguredProject extends Project {
private projectReferences: readonly ProjectReference[] | undefined;
/** Potential project references before the project is actually loaded (read config file) */
/** @internal */
/**
* Potential project references before the project is actually loaded (read config file)
*
* @internal
*/
potentialProjectReferences: Set<string> | undefined;
/** @internal */
@@ -2561,7 +2571,7 @@ export class ConfiguredProject extends Project {
}
/** @internal */
enablePluginsWithOptions(options: CompilerOptions, pluginConfigOverrides: ESMap<string, any> | undefined): void {
enablePluginsWithOptions(options: CompilerOptions, pluginConfigOverrides: Map<string, any> | undefined): void {
this.plugins.length = 0;
if (!options.plugins?.length && !this.projectService.globalPlugins.length) return;
const host = this.projectService.host;
@@ -2630,8 +2640,11 @@ export class ConfiguredProject extends Project {
!this.canConfigFileJsonReportNoInputFiles;
}
/** @internal */
/** Find the configured project from the project references in project which contains the info directly */
/**
* Find the configured project from the project references in project which contains the info directly
*
* @internal
*/
getDefaultChildProjectFromProjectWithReferences(info: ScriptInfo) {
return forEachResolvedProjectReferenceProject(
this,
@@ -2643,8 +2656,11 @@ export class ConfiguredProject extends Project {
);
}
/** Returns true if the project is needed by any of the open script info/external project */
/** @internal */
/**
* Returns true if the project is needed by any of the open script info/external project
*
* @internal
*/
hasOpenRef() {
if (!!this.externalProjectRefCount) {
return true;
@@ -2710,7 +2726,7 @@ export class ExternalProject extends Project {
lastFileExceededProgramSize: string | undefined,
public compileOnSaveEnabled: boolean,
projectFilePath?: string,
pluginConfigOverrides?: ESMap<string, any>,
pluginConfigOverrides?: Map<string, any>,
watchOptions?: WatchOptions) {
super(externalProjectName,
ProjectKind.External,
-2
View File
@@ -5,8 +5,6 @@ import {
TodoComment, TodoCommentDescriptor, TypeAcquisition,
} from "./_namespaces/ts";
/* eslint-disable @typescript-eslint/no-unnecessary-qualifier */
/**
* Declaration module describing the TypeScript Server protocol
*/
+6 -3
View File
@@ -8,7 +8,7 @@ import {
computePositionOfLineAndCharacter, contains, createTextSpanFromBounds, Debug, directorySeparator,
DocumentPositionMapper, DocumentRegistryBucketKeyWithMode, emptyOptions, FileWatcher, FileWatcherEventKind, forEach,
FormatCodeSettings, getBaseFileName, getDefaultFormatCodeSettings, getLineInfo, getScriptKindFromFileName,
getSnapshotText, hasTSFileExtension, IScriptSnapshot, isString, LineInfo, Path, ScriptKind, ScriptSnapshot, Set,
getSnapshotText, hasTSFileExtension, IScriptSnapshot, isString, LineInfo, Path, ScriptKind, ScriptSnapshot,
some, SourceFile, SourceFileLike, stringContains, TextSpan, unorderedRemoveItem,
} from "./_namespaces/ts";
@@ -317,8 +317,11 @@ export class ScriptInfo {
/** @internal */
readonly isDynamic: boolean;
/** @internal */
/** Set to real path if path is different from info.path */
/**
* Set to real path if path is different from info.path
*
* @internal
*/
private realpath: Path | undefined;
/** @internal */
+4 -4
View File
@@ -5,7 +5,7 @@ import {
computeLineAndCharacterOfPosition, computeLineStarts, concatenate, createQueue, createSet, createTextSpan,
createTextSpanFromBounds, Debug, decodedTextSpanIntersectsWith, deduplicate, DefinitionInfo,
DefinitionInfoAndBoundSpan, Diagnostic, diagnosticCategoryName, DiagnosticRelatedInformation, displayPartsToString,
DocumentHighlights, DocumentPosition, DocumentSpan, documentSpansEqual, EmitOutput, equateValues, ESMap,
DocumentHighlights, DocumentPosition, DocumentSpan, documentSpansEqual, EmitOutput, equateValues,
FileTextChanges, filter, find, FindAllReferences, first, firstOrUndefined, flatMap, flatMapToMutable,
flattenDiagnosticMessageText, forEachNameInAccessChainWalkingLeft, FormatCodeSettings, formatting,
getDeclarationFromName, getDeclarationOfKind, getEmitDeclarations, getEntries, getEntrypointsFromPackageJsonInfo,
@@ -14,12 +14,12 @@ import {
getSnapshotText, getSupportedCodeFixes, getTemporaryModuleResolutionState, getTextOfIdentifierOrLiteral,
getTouchingPropertyName, GoToDefinition, HostCancellationToken, identity, ImplementationLocation, ImportSpecifier,
isAccessExpression, isArray, isDeclarationFileName, isIdentifier, isString, isStringLiteralLike,
JSDocLinkDisplayPart, JSDocTagInfo, LanguageServiceMode, LineAndCharacter, map, Map, mapDefined, mapDefinedIterator,
JSDocLinkDisplayPart, JSDocTagInfo, LanguageServiceMode, LineAndCharacter, map, mapDefined, mapDefinedIterator,
mapIterator, mapOneOrMany, memoize, ModuleResolutionKind, MultiMap, NavigateToItem, NavigationBarItem,
NavigationTree, nodeModulesPathPart, normalizePath, OperationCanceledException, OrganizeImportsMode, outFile,
OutliningSpan, Path, perfLogger, PerformanceEvent, PossibleProgramFileInfo, Program, QuickInfo, RefactorEditInfo,
ReferencedSymbol, ReferencedSymbolDefinitionInfo, ReferencedSymbolEntry, ReferenceEntry, removeFileExtension,
RenameInfo, RenameLocation, ScriptKind, SelectionRange, SemanticClassificationFormat, Set, SignatureHelpItem,
RenameInfo, RenameLocation, ScriptKind, SelectionRange, SemanticClassificationFormat, SignatureHelpItem,
SignatureHelpItems, singleIterator, some, SourceFile, startsWith, stringContains, SymbolDisplayPart, SyntaxKind,
TextChange, TextInsertion, TextRange, TextSpan, textSpanEnd, toArray, toFileNameLowerCase, tracing,
unmangleScopedPackageName, UserPreferences, version, WithMetadata,
@@ -537,7 +537,7 @@ function getPerProjectReferences<TResult>(
isForRename: boolean,
getResultsForPosition: (project: Project, location: DocumentPosition) => readonly TResult[] | undefined,
forPositionInResult: (result: TResult, cb: (location: DocumentPosition) => void) => void,
): readonly TResult[] | ESMap<Project, readonly TResult[]> {
): readonly TResult[] | Map<Project, readonly TResult[]> {
// If `getResultsForPosition` returns results for a project, they go in here
const resultsMap = new Map<Project, readonly TResult[]>();
+1 -1
View File
@@ -1,5 +1,5 @@
import {
ApplyCodeActionCommandResult, arrayIsEqualTo, CompilerOptions, getAllowJSCompilerOption, InstallPackageOptions, Map,
ApplyCodeActionCommandResult, arrayIsEqualTo, CompilerOptions, getAllowJSCompilerOption, InstallPackageOptions,
noop, notImplemented, Path, returnFalse, sort, SortedReadonlyArray, TypeAcquisition,
} from "./_namespaces/ts";
import { emptyArray, Project, ProjectService } from "./_namespaces/ts.server";
+1 -1
View File
@@ -1,4 +1,4 @@
import { binarySearch, Comparer, getBaseFileName, identity, Map, perfLogger, SortedArray } from "./_namespaces/ts";
import { binarySearch, Comparer, getBaseFileName, identity, perfLogger, SortedArray } from "./_namespaces/ts";
import { Logger, LogLevel, NormalizedPath, ServerHost } from "./_namespaces/ts.server";
/** @internal */
+1 -1
View File
@@ -1,5 +1,5 @@
import {
getNormalizedAbsolutePath, isRootedDiskPath, Map, normalizePath, Path, SortedArray, SortedReadonlyArray,
getNormalizedAbsolutePath, isRootedDiskPath, normalizePath, Path, SortedArray, SortedReadonlyArray,
TypeAcquisition,
} from "./_namespaces/ts";
import { DiscoverTypings, Project } from "./_namespaces/ts.server";
+1 -1
View File
@@ -8,7 +8,7 @@ import {
JSDocAugmentsTag, JSDocCallbackTag, JSDocEnumTag, JSDocImplementsTag, JSDocParameterTag, JSDocPropertyTag,
JSDocReturnTag, JSDocSeeTag, JSDocTemplateTag, JSDocThisTag, JSDocTypedefTag, JSDocTypeTag, JsxAttribute,
JsxClosingElement, JsxOpeningElement, JsxSelfClosingElement, lastOrUndefined, ModuleDeclaration,
ModuleInstanceState, Node, nodeIsMissing, ParameterDeclaration, parseIsolatedJSDocComment, Push, ReadonlySet,
ModuleInstanceState, Node, nodeIsMissing, ParameterDeclaration, parseIsolatedJSDocComment, Push,
Scanner, ScriptTarget, SemanticMeaning, setParent, some, SourceFile, Symbol, SymbolFlags, SyntaxKind, TextSpan,
textSpanIntersectsWith, TokenClass, TypeChecker, TypeParameterDeclaration,
} from "./_namespaces/ts";
+1 -1
View File
@@ -3,7 +3,7 @@ import {
EndOfLineState, forEachChild, getCombinedModifierFlags, getCombinedNodeFlags, getMeaningFromLocation,
isBindingElement, isCallExpression, isCatchClause, isFunctionDeclaration, isIdentifier, isImportClause,
isImportSpecifier, isInfinityOrNaNString, isJsxElement, isJsxExpression, isJsxSelfClosingElement, isNamespaceImport,
isPropertyAccessExpression, isQualifiedName, isSourceFile, isVariableDeclaration, Map, ModifierFlags,
isPropertyAccessExpression, isQualifiedName, isSourceFile, isVariableDeclaration, ModifierFlags,
NamedDeclaration, Node, NodeFlags, ParameterDeclaration, Program, SemanticMeaning, SourceFile, Symbol, SymbolFlags,
SyntaxKind, TextSpan, textSpanIntersectsWith, Type, TypeChecker, VariableDeclaration,
} from "./_namespaces/ts";
+1 -1
View File
@@ -1,7 +1,7 @@
import {
arrayFrom, cast, CodeActionCommand, CodeFixAction, CodeFixAllContext, CodeFixContext, CodeFixContextBase,
CodeFixRegistration, CombinedCodeActions, computeSuggestionDiagnostics, contains, createMultiMap, Debug, Diagnostic,
DiagnosticAndArguments, diagnosticToString, DiagnosticWithLocation, FileTextChanges, flatMap, isString, map, Map,
DiagnosticAndArguments, diagnosticToString, DiagnosticWithLocation, FileTextChanges, flatMap, isString, map,
Push, TextChange, textChanges,
} from "./_namespaces/ts";
+1 -1
View File
@@ -2,7 +2,7 @@ import {
ArrowFunction, CodeFixAllContext, CodeFixContext, createTextSpanFromNode, Diagnostic, Diagnostics, factory,
FileTextChanges, find, findAncestor, FunctionDeclaration, FunctionExpression, getNodeId, getSyntacticModifierFlags,
getSynthesizedDeepClone, getTokenAtPosition, isArrowFunction, isFunctionDeclaration, isFunctionExpression,
isMethodDeclaration, isNumber, MethodDeclaration, ModifierFlags, Set, some, SourceFile, textChanges, TextSpan,
isMethodDeclaration, isNumber, MethodDeclaration, ModifierFlags, some, SourceFile, textChanges, TextSpan,
textSpanEnd, textSpansEqual,
} from "../_namespaces/ts";
import { codeFixAll, createCodeFixAction, registerCodeFix } from "../_namespaces/ts.codefix";
+1 -1
View File
@@ -3,7 +3,7 @@ import {
factory, FileTextChanges, find, FindAllReferences, findAncestor, findPrecedingToken, forEach, getAncestor,
getFixableErrorSpanExpression, getSymbolId, hasSyntacticModifier, Identifier, isArrowFunction, isBinaryExpression,
isBlock, isCallOrNewExpression, isForOfStatement, isIdentifier, isNumber, isPropertyAccessExpression,
isVariableDeclaration, ModifierFlags, Node, NodeFlags, positionIsASICandidate, Program, Set, some, SourceFile,
isVariableDeclaration, ModifierFlags, Node, NodeFlags, positionIsASICandidate, Program, some, SourceFile,
Symbol, SyntaxKind, textChanges, TextSpan, textSpansEqual, tryAddToSet, tryCast, TypeChecker, TypeFlags,
} from "../_namespaces/ts";
import {
+1 -1
View File
@@ -1,6 +1,6 @@
import {
Diagnostics, every, Expression, findAncestor, getTokenAtPosition, isArrayLiteralExpression, isAssignmentExpression,
isBinaryExpression, isExpressionStatement, isForInOrOfStatement, isIdentifier, Node, Program, Set, SourceFile,
isBinaryExpression, isExpressionStatement, isForInOrOfStatement, isIdentifier, Node, Program, SourceFile,
SyntaxKind, textChanges, tryAddToSet, TypeChecker,
} from "../_namespaces/ts";
import { codeFixAll, createCodeFixAction, registerCodeFix } from "../_namespaces/ts.codefix";
@@ -1,5 +1,5 @@
import {
Diagnostics, getTokenAtPosition, isIdentifier, Node, Set, SourceFile, SyntaxKind, textChanges, tryAddToSet,
Diagnostics, getTokenAtPosition, isIdentifier, Node, SourceFile, SyntaxKind, textChanges, tryAddToSet,
} from "../_namespaces/ts";
import { codeFixAll, createCodeFixAction, registerCodeFix } from "../_namespaces/ts.codefix";
+1 -1
View File
@@ -1,5 +1,5 @@
import {
addToSeen, Diagnostics, factory, findChildOfKind, getSymbolId, getTokenAtPosition, isVariableDeclarationList, Map,
addToSeen, Diagnostics, factory, findChildOfKind, getSymbolId, getTokenAtPosition, isVariableDeclarationList,
Program, SourceFile, Symbol, SyntaxKind, textChanges, Token, tryCast,
} from "../_namespaces/ts";
import {
@@ -1,15 +1,15 @@
import {
ArrowFunction, AwaitExpression, BindingName, BindingPattern, Block, CallExpression, canBeConvertedToAsync,
CodeFixContext, concatenate, createMultiMap, Debug, Diagnostics, elementAt, emptyArray, ESMap, every, Expression,
CodeFixContext, concatenate, createMultiMap, Debug, Diagnostics, elementAt, emptyArray, every, Expression,
factory, firstOrUndefined, flatMap, forEach, forEachChild, forEachReturnStatement, FunctionExpression,
FunctionLikeDeclaration, GeneratedIdentifierFlags, getContainingFunction, getNodeId, getObjectFlags,
getOriginalNode, getSymbolId, getSynthesizedDeepClone, getSynthesizedDeepCloneWithReplacements, getTokenAtPosition,
hasPropertyAccessExpressionWithName, Identifier, idText, isBindingElement, isBlock, isCallExpression, isExpression,
isFixablePromiseHandler, isFunctionLike, isFunctionLikeDeclaration, isGeneratedIdentifier, isIdentifier, isInJSFile,
isObjectBindingPattern, isOmittedExpression, isParameter, isPropertyAccessExpression, isReturnStatement,
isReturnStatementWithFixablePromiseHandler, isVariableDeclaration, lastOrUndefined, Map, moveRangePastModifiers,
Node, NodeFlags, ObjectFlags, PropertyAccessExpression, ReadonlyESMap, ReadonlySet, returnsPromise, ReturnStatement,
returnTrue, Set, Signature, SignatureKind, skipTrivia, SourceFile, Statement, Symbol, SyntaxKind, textChanges,
isReturnStatementWithFixablePromiseHandler, isVariableDeclaration, lastOrUndefined, moveRangePastModifiers,
Node, NodeFlags, ObjectFlags, PropertyAccessExpression, returnsPromise, ReturnStatement,
returnTrue, Signature, SignatureKind, skipTrivia, SourceFile, Statement, Symbol, SyntaxKind, textChanges,
tryCast, TryStatement, Type, TypeChecker, TypeNode, TypeReference, UnionReduction,
} from "../_namespaces/ts";
import { codeFixAll, createCodeFixAction, registerCodeFix } from "../_namespaces/ts.codefix";
@@ -53,7 +53,7 @@ interface SynthIdentifier {
interface Transformer {
readonly checker: TypeChecker;
readonly synthNamesMap: ESMap<string, SynthIdentifier>; // keys are the symbol id of the identifier
readonly synthNamesMap: Map<string, SynthIdentifier>; // keys are the symbol id of the identifier
readonly setOfExpressionsToReturn: ReadonlySet<number>; // keys are the node ids of the expressions
readonly isInJSFile: boolean;
}
@@ -213,7 +213,7 @@ function isPromiseTypedExpression(node: Node, checker: TypeChecker): node is Exp
This function collects all existing identifier names and names of identifiers that will be created in the refactor.
It then checks for any collisions and renames them through getSynthesizedDeepClone
*/
function renameCollidingVarNames(nodeToRename: FunctionLikeDeclaration, checker: TypeChecker, synthNamesMap: ESMap<string, SynthIdentifier>): FunctionLikeDeclaration {
function renameCollidingVarNames(nodeToRename: FunctionLikeDeclaration, checker: TypeChecker, synthNamesMap: Map<string, SynthIdentifier>): FunctionLikeDeclaration {
const identsToRenameMap = new Map<string, Identifier>(); // key is the symbol id
const collidingSymbolMap = createMultiMap<Symbol>();
forEachChild(nodeToRename, function visit(node: Node) {
@@ -286,7 +286,7 @@ function renameCollidingVarNames(nodeToRename: FunctionLikeDeclaration, checker:
});
}
function getNewNameIfConflict(name: Identifier, originalNames: ReadonlyESMap<string, Symbol[]>): SynthIdentifier {
function getNewNameIfConflict(name: Identifier, originalNames: ReadonlyMap<string, Symbol[]>): SynthIdentifier {
const numVarsSameName = (originalNames.get(name.text) || emptyArray).length;
const identifier = numVarsSameName === 0 ? name : factory.createIdentifier(name.text + "_" + numVarsSameName);
return createSynthIdentifier(identifier);
+20 -20
View File
@@ -3,17 +3,17 @@ import {
} from "../_namespaces/ts.codefix";
import {
__String, arrayFrom, ArrowFunction, BinaryExpression, BindingElement, BindingName, ClassDeclaration,
ClassExpression, concatenate, copyEntries, createMultiMap, createRange, Debug, Diagnostics, emptyMap, ESMap,
ClassExpression, concatenate, copyEntries, createMultiMap, createRange, Debug, Diagnostics, emptyMap,
ExportDeclaration, ExportSpecifier, Expression, ExpressionStatement, factory, filter, findChildOfKind, flatMap,
forEach, FunctionDeclaration, FunctionExpression, getEmitScriptTarget, getModeForUsageLocation, getQuotePreference,
getResolvedModule, getSynthesizedDeepClone, getSynthesizedDeepClones, getSynthesizedDeepClonesWithReplacements,
getSynthesizedDeepCloneWithReplacements, Identifier, ImportDeclaration, importFromModuleSpecifier, ImportSpecifier,
InternalSymbolName, isArray, isArrowFunction, isBinaryExpression, isClassExpression,
isExportsOrModuleExportsOrAlias, isFunctionExpression, isIdentifier, isNonContextualKeyword,
isObjectLiteralExpression, isPropertyAccessExpression, isRequireCall, isVariableStatement, makeImport, map, Map,
isObjectLiteralExpression, isPropertyAccessExpression, isRequireCall, isVariableStatement, makeImport, map,
mapAllOrFail, mapIterator, MethodDeclaration, Modifier, Node, NodeArray, NodeFlags, ObjectLiteralElementLike,
ObjectLiteralExpression, PropertyAccessExpression, QuotePreference, rangeContainsRange, ReadonlyCollection,
ReadonlyESMap, ScriptTarget, Set, some, SourceFile, Statement, StringLiteralLike, SymbolFlags, SyntaxKind,
ScriptTarget, some, SourceFile, Statement, StringLiteralLike, SymbolFlags, SyntaxKind,
textChanges, TypeChecker, VariableStatement,
} from "../_namespaces/ts";
@@ -61,7 +61,7 @@ function convertFileToEsModule(sourceFile: SourceFile, checker: TypeChecker, cha
const exports = collectExportRenames(sourceFile, checker, identifiers);
convertExportsAccesses(sourceFile, exports, changes);
let moduleExportsChangedToDefault = false;
let useSitesToUnqualify: ESMap<Node, Node> | undefined;
let useSitesToUnqualify: Map<Node, Node> | undefined;
// Process variable statements first to collect use sites that need to be updated inside other transformations
for (const statement of filter(sourceFile.statements, isVariableStatement)) {
const newUseSites = convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference);
@@ -91,7 +91,7 @@ function convertFileToEsModule(sourceFile: SourceFile, checker: TypeChecker, cha
* export { _x as x };
* This conversion also must place if the exported name is not a valid identifier, e.g. `exports.class = 0;`.
*/
type ExportRenames = ReadonlyESMap<string, string>;
type ExportRenames = ReadonlyMap<string, string>;
function collectExportRenames(sourceFile: SourceFile, checker: TypeChecker, identifiers: Identifiers): ExportRenames {
const res = new Map<string, string>();
@@ -137,7 +137,7 @@ function convertStatement(
identifiers: Identifiers,
target: ScriptTarget,
exports: ExportRenames,
useSitesToUnqualify: ESMap<Node, Node> | undefined,
useSitesToUnqualify: Map<Node, Node> | undefined,
quotePreference: QuotePreference
): ModuleExportsChanged {
switch (statement.kind) {
@@ -174,7 +174,7 @@ function convertVariableStatement(
identifiers: Identifiers,
target: ScriptTarget,
quotePreference: QuotePreference,
): ESMap<Node, Node> | undefined {
): Map<Node, Node> | undefined {
const { declarationList } = statement;
let foundImport = false;
const converted = map(declarationList.declarations, decl => {
@@ -200,7 +200,7 @@ function convertVariableStatement(
if (foundImport) {
// useNonAdjustedEndPosition to ensure we don't eat the newline after the statement.
changes.replaceNodeWithNodes(sourceFile, statement, flatMap(converted, c => c.newImports));
let combinedUseSites: ESMap<Node, Node> | undefined;
let combinedUseSites: Map<Node, Node> | undefined;
forEach(converted, c => {
if (c.useSitesToUnqualify) {
copyEntries(c.useSitesToUnqualify, combinedUseSites ??= new Map());
@@ -237,7 +237,7 @@ function convertAssignment(
assignment: BinaryExpression,
changes: textChanges.ChangeTracker,
exports: ExportRenames,
useSitesToUnqualify: ESMap<Node, Node> | undefined,
useSitesToUnqualify: Map<Node, Node> | undefined,
): ModuleExportsChanged {
const { left, right } = assignment;
if (!isPropertyAccessExpression(left)) {
@@ -274,7 +274,7 @@ function convertAssignment(
* Convert `module.exports = { ... }` to individual exports..
* We can't always do this if the module has interesting members -- then it will be a default export instead.
*/
function tryChangeModuleExportsObject(object: ObjectLiteralExpression, useSitesToUnqualify: ESMap<Node, Node> | undefined): [readonly Statement[], ModuleExportsChanged] | undefined {
function tryChangeModuleExportsObject(object: ObjectLiteralExpression, useSitesToUnqualify: Map<Node, Node> | undefined): [readonly Statement[], ModuleExportsChanged] | undefined {
const statements = mapAllOrFail(object.properties, prop => {
switch (prop.kind) {
case SyntaxKind.GetAccessor:
@@ -357,7 +357,7 @@ function convertExportsPropertyAssignment({ left, right, parent }: BinaryExpress
}
// TODO: GH#22492 this will cause an error if a change has been made inside the body of the node.
function convertExportsDotXEquals_replaceNode(name: string | undefined, exported: Expression, useSitesToUnqualify: ESMap<Node, Node> | undefined): Statement {
function convertExportsDotXEquals_replaceNode(name: string | undefined, exported: Expression, useSitesToUnqualify: Map<Node, Node> | undefined): Statement {
const modifiers = [factory.createToken(SyntaxKind.ExportKeyword)];
switch (exported.kind) {
case SyntaxKind.FunctionExpression: {
@@ -385,9 +385,9 @@ function convertExportsDotXEquals_replaceNode(name: string | undefined, exported
}
}
function replaceImportUseSites<T extends Node>(node: T, useSitesToUnqualify: ESMap<Node, Node> | undefined): T;
function replaceImportUseSites<T extends Node>(nodes: NodeArray<T>, useSitesToUnqualify: ESMap<Node, Node> | undefined): NodeArray<T>;
function replaceImportUseSites<T extends Node>(nodeOrNodes: T | NodeArray<T>, useSitesToUnqualify: ESMap<Node, Node> | undefined) {
function replaceImportUseSites<T extends Node>(node: T, useSitesToUnqualify: Map<Node, Node> | undefined): T;
function replaceImportUseSites<T extends Node>(nodes: NodeArray<T>, useSitesToUnqualify: Map<Node, Node> | undefined): NodeArray<T>;
function replaceImportUseSites<T extends Node>(nodeOrNodes: T | NodeArray<T>, useSitesToUnqualify: Map<Node, Node> | undefined) {
if (!useSitesToUnqualify || !some(arrayFrom(useSitesToUnqualify.keys()), original => rangeContainsRange(nodeOrNodes, original))) {
return nodeOrNodes;
}
@@ -461,7 +461,7 @@ function convertSingleIdentifierImport(name: Identifier, moduleSpecifier: String
const namedBindingsNames = new Map<string, string>();
// True if there is some non-property use like `x()` or `f(x)`.
let needDefaultImport = false;
let useSitesToUnqualify: ESMap<Node, Node> | undefined;
let useSitesToUnqualify: Map<Node, Node> | undefined;
for (const use of identifiers.original.get(name.text)!) {
if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
@@ -527,7 +527,7 @@ interface Identifiers {
readonly additional: Set<string>;
}
type FreeIdentifiers = ReadonlyESMap<string, readonly Identifier[]>;
type FreeIdentifiers = ReadonlyMap<string, readonly Identifier[]>;
function collectFreeIdentifiers(file: SourceFile): FreeIdentifiers {
const map = createMultiMap<Identifier>();
forEachFreeIdentifier(file, id => map.add(id.text, id));
@@ -559,7 +559,7 @@ function isFreeIdentifier(node: Identifier): boolean {
// Node helpers
function functionExpressionToDeclaration(name: string | undefined, additionalModifiers: readonly Modifier[], fn: FunctionExpression | ArrowFunction | MethodDeclaration, useSitesToUnqualify: ESMap<Node, Node> | undefined): FunctionDeclaration {
function functionExpressionToDeclaration(name: string | undefined, additionalModifiers: readonly Modifier[], fn: FunctionExpression | ArrowFunction | MethodDeclaration, useSitesToUnqualify: Map<Node, Node> | undefined): FunctionDeclaration {
return factory.createFunctionDeclaration(
concatenate(additionalModifiers, getSynthesizedDeepClones(fn.modifiers)),
getSynthesizedDeepClone(fn.asteriskToken),
@@ -570,7 +570,7 @@ function functionExpressionToDeclaration(name: string | undefined, additionalMod
factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body!, useSitesToUnqualify)));
}
function classExpressionToDeclaration(name: string | undefined, additionalModifiers: readonly Modifier[], cls: ClassExpression, useSitesToUnqualify: ESMap<Node, Node> | undefined): ClassDeclaration {
function classExpressionToDeclaration(name: string | undefined, additionalModifiers: readonly Modifier[], cls: ClassExpression, useSitesToUnqualify: Map<Node, Node> | undefined): ClassDeclaration {
return factory.createClassDeclaration(
concatenate(additionalModifiers, getSynthesizedDeepClones(cls.modifiers)),
name,
@@ -607,10 +607,10 @@ function makeExportDeclaration(exportSpecifiers: ExportSpecifier[] | undefined,
interface ConvertedImports {
newImports: readonly Node[];
useSitesToUnqualify?: ESMap<Node, Node>;
useSitesToUnqualify?: Map<Node, Node>;
}
function convertedImports(newImports: readonly Node[], useSitesToUnqualify?: ESMap<Node, Node>): ConvertedImports {
function convertedImports(newImports: readonly Node[], useSitesToUnqualify?: Map<Node, Node>): ConvertedImports {
return {
newImports,
useSitesToUnqualify
@@ -1,6 +1,6 @@
import {
addToSeen, CodeFixContextBase, contains, createTextSpanFromNode, Diagnostics, ExportSpecifier, factory, filter,
findDiagnosticForNode, getDiagnosticsWithinSpan, getNodeId, getTokenAtPosition, isExportSpecifier, Map, SourceFile,
findDiagnosticForNode, getDiagnosticsWithinSpan, getNodeId, getTokenAtPosition, isExportSpecifier, SourceFile,
SyntaxKind, textChanges, TextSpan, tryCast,
} from "../_namespaces/ts";
import { codeFixAll, createCodeFixAction, registerCodeFix } from "../_namespaces/ts.codefix";
@@ -1,6 +1,6 @@
import {
CodeFixAction, createTextChange, createTextSpan, createTextSpanFromBounds, DiagnosticCategory, Diagnostics,
getLineAndCharacterOfPosition, getNewLineOrDefaultFromHost, isCheckJsEnabledForFile, isInJSFile, mapDefined, Set,
getLineAndCharacterOfPosition, getNewLineOrDefaultFromHost, isCheckJsEnabledForFile, isInJSFile, mapDefined,
SourceFile, textChanges, tryAddToSet,
} from "../_namespaces/ts";
import {
@@ -1,7 +1,7 @@
import {
addToSeen, createTextSpan, DiagnosticMessageChain, Diagnostics, factory, find, flattenDiagnosticMessageText,
getEmitScriptTarget, getNodeId, getTokenAtPosition, isExpression, isIdentifier, isMappedTypeNode, isString,
isTypeNode, isTypeParameterDeclaration, LanguageServiceHost, Map, Node, Program, SourceFile, textChanges, TextSpan,
isTypeNode, isTypeParameterDeclaration, LanguageServiceHost, Node, Program, SourceFile, textChanges, TextSpan,
Type, TypeChecker, TypeParameterDeclaration, UserPreferences,
} from "../_namespaces/ts";
import {
@@ -11,9 +11,9 @@ import {
isMemberName, isMethodDeclaration, isMethodSignature, isModuleDeclaration, isObjectLiteralExpression, isParameter,
isPrivateIdentifier, isPropertyAccessExpression, isPropertyDeclaration, isReturnStatement, isSourceFile,
isSourceFileFromLibrary, isSourceFileJS, isTransientSymbol, isTypeLiteralNode, JsxOpeningLikeElement,
LanguageVariant, length, map, Map, MethodDeclaration, ModifierFlags, ModuleDeclaration, Node, NodeBuilderFlags,
LanguageVariant, length, map, MethodDeclaration, ModifierFlags, ModuleDeclaration, Node, NodeBuilderFlags,
NumberLiteralType, ObjectFlags, ObjectLiteralExpression, or, PrivateIdentifier, Program, PropertyDeclaration,
QuotePreference, ReturnStatement, ScriptTarget, Set, setParent, Signature, SignatureKind, singleElementArray,
QuotePreference, ReturnStatement, ScriptTarget, setParent, Signature, SignatureKind, singleElementArray,
singleOrUndefined, skipConstraint, some, SourceFile, startsWithUnderscore, StringLiteralType, Symbol, SymbolFlags,
SyntaxKind, textChanges, tryCast, Type, TypeChecker, TypeFlags, TypeLiteralNode, TypeNode, TypeReference, UnionType,
} from "../_namespaces/ts";
@@ -1,7 +1,7 @@
import {
CodeFixAllContext, Diagnostics, factory, getJSDocTypeTag, getTokenAtPosition, idText, isCallExpression,
isIdentifier, isInJSFile, isNewExpression, isParameter, isParenthesizedExpression, isParenthesizedTypeNode,
isTypeReferenceNode, isUnionTypeNode, NewExpression, ParameterDeclaration, Program, Set, skipTrivia, some,
isTypeReferenceNode, isUnionTypeNode, NewExpression, ParameterDeclaration, Program, skipTrivia, some,
SourceFile, SyntaxKind, textChanges, TextSpan, TypeFlags,
} from "../_namespaces/ts";
import { codeFixAll, createCodeFixAction, registerCodeFix } from "../_namespaces/ts.codefix";
@@ -85,4 +85,4 @@ function getEffectiveTypeArguments(node: NewExpression) {
else {
return node.typeArguments;
}
}
}
@@ -1,7 +1,7 @@
import {
addToSeen, ArrowFunction, Diagnostics, factory, findChildOfKind, first, FunctionDeclaration, FunctionExpression,
getContainingFunction, getEntityNameFromTypeNode, getNodeId, getTokenAtPosition, isFunctionTypeNode,
isVariableDeclaration, Map, MethodDeclaration, Node, SourceFile, SyntaxKind, textChanges, TypeNode,
isVariableDeclaration, MethodDeclaration, Node, SourceFile, SyntaxKind, textChanges, TypeNode,
} from "../_namespaces/ts";
import { codeFixAll, createCodeFixAction, registerCodeFix } from "../_namespaces/ts.codefix";
@@ -1,6 +1,6 @@
import {
addToSeen, cast, ClassElement, ClassLikeDeclaration, Diagnostics, first, getEffectiveBaseTypeNode, getNodeId,
getSyntacticModifierFlags, getTokenAtPosition, isClassLike, Map, ModifierFlags, SourceFile, Symbol, textChanges,
getSyntacticModifierFlags, getTokenAtPosition, isClassLike, ModifierFlags, SourceFile, Symbol, textChanges,
UserPreferences,
} from "../_namespaces/ts";
import {
@@ -2,7 +2,7 @@ import {
addToSeen, and, ClassElement, ClassLikeDeclaration, CodeFixAction, createSymbolTable, Debug, Diagnostics,
ExpressionWithTypeArguments, find, getContainingClass, getEffectiveBaseTypeNode, getEffectiveImplementsTypeNodes,
getEffectiveModifierFlags, getNodeId, getTokenAtPosition, IndexKind, InterfaceDeclaration, InterfaceType,
isConstructorDeclaration, Map, mapDefined, ModifierFlags, SourceFile, Symbol, SymbolTable, textChanges, TypeChecker,
isConstructorDeclaration, mapDefined, ModifierFlags, SourceFile, Symbol, SymbolTable, textChanges, TypeChecker,
UserPreferences,
} from "../_namespaces/ts";
import {
@@ -1,7 +1,7 @@
import {
addToSeen, CallExpression, ConstructorDeclaration, Diagnostics, ExpressionStatement, forEachChild,
getContainingFunction, getNodeId, getTokenAtPosition, isExpressionStatement, isFunctionLike,
isPropertyAccessExpression, isSuperCall, Map, Node, SourceFile, SyntaxKind, textChanges,
isPropertyAccessExpression, isSuperCall, Node, SourceFile, SyntaxKind, textChanges,
} from "../_namespaces/ts";
import { codeFixAll, createCodeFixAction, registerCodeFix } from "../_namespaces/ts.codefix";
@@ -2,7 +2,7 @@ import {
canHaveExportModifier, Declaration, Diagnostics, ExportDeclaration, factory, find, findAncestor, findLast,
firstOrUndefined, getResolvedModule, getTokenAtPosition, Identifier, isExportDeclaration, isIdentifier,
isImportDeclaration, isNamedExports, isSourceFileFromLibrary, isStringLiteral, isTypeDeclaration,
isVariableDeclaration, isVariableStatement, length, map, Map, Node, Program, SourceFile, Symbol, textChanges,
isVariableDeclaration, isVariableStatement, length, map, Node, Program, SourceFile, Symbol, textChanges,
tryCast, VariableStatement,
} from "../_namespaces/ts";
import {

Some files were not shown because too many files have changed in this diff Show More