diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 9cf1c9d8f3f..f3c59a61717 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -7,7 +7,7 @@ // ${cwd}: the current working directory of the spawned process { "version": "0.1.0", - "command": "jake", + "command": "gulp", "isShellCommand": true, "showOutput": "silent", "tasks": [ @@ -18,25 +18,6 @@ "problemMatcher": [ "$tsc" ] - }, - { - "taskName": "lint-server", - "args": [], - "problemMatcher": { - "owner": "typescript", - "fileLocation": ["relative", "${workspaceRoot}"], - "pattern": { - "regexp": "^(warning|error)\\s+([^(]+)\\s+\\((\\d+|\\d+,\\d+|\\d+,\\d+,\\d+,\\d+)\\):\\s+(.*)$", - "severity": 1, - "file": 2, - "location": 3, - "message": 4 - }, - "watchedTaskBeginsRegExp": "^\\*\\*\\*Lint failure\\*\\*\\*$", - "watchedTaskEndsRegExp": "^\\*\\*\\* Total \\d+ failures\\.$" - }, - "showOutput": "always", - "isWatching": true } ] } \ No newline at end of file diff --git a/Gulpfile.ts b/Gulpfile.ts new file mode 100644 index 00000000000..2e6081bea4a --- /dev/null +++ b/Gulpfile.ts @@ -0,0 +1,1044 @@ +/// +/// + +import * as cp from "child_process"; +import * as path from "path"; +import * as fs from "fs"; +import originalGulp = require("gulp"); +import helpMaker = require("gulp-help"); +import runSequence = require("run-sequence"); +import concat = require("gulp-concat"); +import clone = require("gulp-clone"); +import newer = require("gulp-newer"); +import tsc = require("gulp-typescript"); +declare module "gulp-typescript" { + interface Settings { + stripInternal?: boolean; + newLine?: string; + } + interface CompileStream extends NodeJS.ReadWriteStream {} // Either gulp or gulp-typescript has some odd typings which don't reflect reality, making this required +} +import * as insert from "gulp-insert"; +import * as sourcemaps from "gulp-sourcemaps"; +declare global { + // This is silly. We include Q because orchestrator (a part of gulp) depends on it, but its not included. + // `del` further depends on `Promise` (and is also not included), so we just, patch the global scope's Promise to Q's + type Promise = Q.Promise; +} +import del = require("del"); +import mkdirP = require("mkdirp"); +import minimist = require("minimist"); +import browserify = require("browserify"); +import through2 = require("through2"); +import merge2 = require("merge2"); +import intoStream = require("into-stream"); +import * as os from "os"; +import Linter = require("tslint"); +const gulp = helpMaker(originalGulp); +const mochaParallel = require("./scripts/mocha-parallel.js"); +const {runTestsInParallel} = mochaParallel; + +const cmdLineOptions = minimist(process.argv.slice(2), { + boolean: ["debug", "light", "colors", "lint", "soft"], + string: ["browser", "tests", "host", "reporter"], + alias: { + d: "debug", + t: "tests", + test: "tests", + r: "reporter", + color: "colors", + f: "files", + file: "files" + }, + default: { + soft: false, + colors: process.env.colors || process.env.color || true, + debug: process.env.debug || process.env.d, + host: process.env.TYPESCRIPT_HOST || process.env.host || "node", + browser: process.env.browser || process.env.b || "IE", + tests: process.env.test || process.env.tests || process.env.t, + light: process.env.light || false, + port: process.env.port || process.env.p || "8888", + reporter: process.env.reporter || process.env.r, + lint: process.env.lint || true, + files: process.env.f || process.env.file || process.env.files || "", + } +}); + +function exec(cmd: string, args: string[], complete: () => void = (() => {}), error: (e: any, status: number) => void = (() => {})) { + console.log(`${cmd} ${args.join(" ")}`); + // TODO (weswig): Update child_process types to add windowsVerbatimArguments to the type definition + const subshellFlag = isWin ? "/c" : "-c"; + const command = isWin ? [cmd, ...args] : [`${cmd} ${args.join(" ")}`]; + const ex = cp.spawn(isWin ? "cmd" : "/bin/sh", [subshellFlag, ...command], { stdio: "inherit", windowsVerbatimArguments: true } as any); + ex.on("exit", (code) => code === 0 ? complete() : error(/*e*/ undefined, code)); + ex.on("error", error); +} + + +let useDebugMode = true; +let host = cmdLineOptions["host"]; + +// Constants +const compilerDirectory = "src/compiler/"; +const servicesDirectory = "src/services/"; +const serverDirectory = "src/server/"; +const harnessDirectory = "src/harness/"; +const libraryDirectory = "src/lib/"; +const scriptsDirectory = "scripts/"; +const unittestsDirectory = "tests/cases/unittests/"; +const docDirectory = "doc/"; + +const builtDirectory = "built/"; +const builtLocalDirectory = "built/local/"; +const LKGDirectory = "lib/"; + +const copyright = "CopyrightNotice.txt"; + +const compilerFilename = "tsc.js"; +const LKGCompiler = path.join(LKGDirectory, compilerFilename); +const builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename); + +const nodeModulesPathPrefix = path.resolve("./node_modules/.bin/"); +const isWin = /^win/.test(process.platform); +const mocha = path.join(nodeModulesPathPrefix, "mocha") + (isWin ? ".cmd" : ""); + +const compilerSources = require("./src/compiler/tsconfig.json").files.map((file) => path.join(compilerDirectory, file)); + +const servicesSources = require("./src/services/tsconfig.json").files.map((file) => path.join(servicesDirectory, file)); + +const serverCoreSources = require("./src/server/tsconfig.json").files.map((file) => path.join(serverDirectory, file)); + +const languageServiceLibrarySources = [ + "editorServices.ts", + "protocol.d.ts", + "session.ts" +].map(function (f) { + return path.join(serverDirectory, f); +}).concat(servicesSources); + +const harnessCoreSources = [ + "harness.ts", + "sourceMapRecorder.ts", + "harnessLanguageService.ts", + "fourslash.ts", + "runnerbase.ts", + "compilerRunner.ts", + "typeWriter.ts", + "fourslashRunner.ts", + "projectsRunner.ts", + "loggedIO.ts", + "rwcRunner.ts", + "test262Runner.ts", + "runner.ts" +].map(function (f) { + return path.join(harnessDirectory, f); +}); + +const harnessSources = harnessCoreSources.concat([ + "incrementalParser.ts", + "jsDocParsing.ts", + "services/colorization.ts", + "services/documentRegistry.ts", + "services/preProcessFile.ts", + "services/patternMatcher.ts", + "session.ts", + "versionCache.ts", + "convertToBase64.ts", + "transpile.ts", + "reuseProgramStructure.ts", + "cachingInServerLSHost.ts", + "moduleResolution.ts", + "tsconfigParsing.ts", + "commandLineParsing.ts", + "convertCompilerOptionsFromJson.ts", + "convertTypingOptionsFromJson.ts", + "tsserverProjectSystem.ts", + "matchFiles.ts", +].map(function (f) { + return path.join(unittestsDirectory, f); +})).concat([ + "protocol.d.ts", + "session.ts", + "client.ts", + "editorServices.ts" +].map(function (f) { + return path.join(serverDirectory, f); +})); + +const es2015LibrarySources = [ + "es2015.core.d.ts", + "es2015.collection.d.ts", + "es2015.generator.d.ts", + "es2015.iterable.d.ts", + "es2015.promise.d.ts", + "es2015.proxy.d.ts", + "es2015.reflect.d.ts", + "es2015.symbol.d.ts", + "es2015.symbol.wellknown.d.ts" +]; + +const es2015LibrarySourceMap = es2015LibrarySources.map(function(source) { + return { target: "lib." + source, sources: ["header.d.ts", source] }; +}); + +const es2016LibrarySource = [ "es2016.array.include.d.ts" ]; + +const es2016LibrarySourceMap = es2016LibrarySource.map(function (source) { + return { target: "lib." + source, sources: ["header.d.ts", source] }; +}); + +const es2017LibrarySource = [ + "es2017.object.d.ts", + "es2017.sharedmemory.d.ts" +]; + +const es2017LibrarySourceMap = es2017LibrarySource.map(function (source) { + return { target: "lib." + source, sources: ["header.d.ts", source] }; +}); + +const hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"]; + +const librarySourceMap = [ + // Host library + { target: "lib.dom.d.ts", sources: ["header.d.ts", "dom.generated.d.ts"] }, + { target: "lib.dom.iterable.d.ts", sources: ["header.d.ts", "dom.iterable.d.ts"] }, + { target: "lib.webworker.d.ts", sources: ["header.d.ts", "webworker.generated.d.ts"] }, + { target: "lib.scripthost.d.ts", sources: ["header.d.ts", "scripthost.d.ts"] }, + + // JavaScript library + { target: "lib.es5.d.ts", sources: ["header.d.ts", "es5.d.ts"] }, + { target: "lib.es2015.d.ts", sources: ["header.d.ts", "es2015.d.ts"] }, + { target: "lib.es2016.d.ts", sources: ["header.d.ts", "es2016.d.ts"] }, + { target: "lib.es2017.d.ts", sources: ["header.d.ts", "es2017.d.ts"] }, + + // JavaScript + all host library + { target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources) }, + { target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") } +].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap); + +const libraryTargets = librarySourceMap.map(function (f) { + return path.join(builtLocalDirectory, f.target); +}); + +for (const i in libraryTargets) { + const entry = librarySourceMap[i]; + const target = libraryTargets[i]; + const sources = [copyright].concat(entry.sources.map(function (s) { + return path.join(libraryDirectory, s); + })); + gulp.task(target, false, [], function() { + return gulp.src(sources) + .pipe(newer(target)) + .pipe(concat(target, { newLine: "" })) + .pipe(gulp.dest(".")); + }); +} + +const configureNightlyJs = path.join(scriptsDirectory, "configureNightly.js"); +const configureNightlyTs = path.join(scriptsDirectory, "configureNightly.ts"); +const packageJson = "package.json"; +const programTs = path.join(compilerDirectory, "program.ts"); + +function needsUpdate(source: string | string[], dest: string | string[]): boolean { + if (typeof source === "string" && typeof dest === "string") { + if (fs.existsSync(dest)) { + const {mtime: outTime} = fs.statSync(dest); + const {mtime: inTime} = fs.statSync(source); + if (+inTime <= +outTime) { + return false; + } + } + } + else if (typeof source === "string" && typeof dest !== "string") { + const {mtime: inTime} = fs.statSync(source); + for (const filepath of dest) { + if (fs.existsSync(filepath)) { + const {mtime: outTime} = fs.statSync(filepath); + if (+inTime > +outTime) { + return true; + } + } + else { + return true; + } + } + return false; + } + else if (typeof source !== "string" && typeof dest === "string") { + if (fs.existsSync(dest)) { + const {mtime: outTime} = fs.statSync(dest); + for (const filepath of source) { + if (fs.existsSync(filepath)) { + const {mtime: inTime} = fs.statSync(filepath); + if (+inTime > +outTime) { + return true; + } + } + else { + return true; + } + } + return false; + } + } + else if (typeof source !== "string" && typeof dest !== "string") { + for (let i = 0; i < source.length; i++) { + if (!dest[i]) { + continue; + } + if (fs.existsSync(dest[i])) { + const {mtime: outTime} = fs.statSync(dest[i]); + const {mtime: inTime} = fs.statSync(source[i]); + if (+inTime > +outTime) { + return true; + } + } + else { + return true; + } + } + return false; + } + return true; +} + +function getCompilerSettings(base: tsc.Settings, useBuiltCompiler?: boolean): tsc.Settings { + const copy: tsc.Settings = {}; + for (const key in base) { + copy[key] = base[key]; + } + if (!useDebugMode) { + if (copy.removeComments === undefined) copy.removeComments = true; + copy.newLine = "lf"; + } + else { + copy.preserveConstEnums = true; + } + if (useBuiltCompiler === true) { + copy.typescript = require("./built/local/typescript.js"); + } + else if (useBuiltCompiler === false) { + copy.typescript = require("./lib/typescript.js"); + } + return copy; +} + +gulp.task(configureNightlyJs, false, [], () => { + const settings: tsc.Settings = { + declaration: false, + removeComments: true, + noResolve: false, + stripInternal: false, + }; + return gulp.src(configureNightlyTs) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(path.dirname(configureNightlyJs))) + .pipe(gulp.dest(path.dirname(configureNightlyJs))); +}); + + +// Nightly management tasks +gulp.task("configure-nightly", "Runs scripts/configureNightly.ts to prepare a build for nightly publishing", [configureNightlyJs], (done) => { + exec(host, [configureNightlyJs, packageJson, programTs], done, done); +}); +gulp.task("publish-nightly", "Runs `npm publish --tag next` to create a new nightly build on npm", ["LKG"], () => { + return runSequence("clean", "useDebugMode", "runtests", (done) => { + exec("npm", ["publish", "--tag", "next"], done, done); + }); +}); + +const importDefinitelyTypedTestsDirectory = path.join(scriptsDirectory, "importDefinitelyTypedTests"); +const importDefinitelyTypedTestsJs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.js"); +const importDefinitelyTypedTestsTs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.ts"); + +gulp.task(importDefinitelyTypedTestsJs, false, [], () => { + const settings: tsc.Settings = getCompilerSettings({ + declaration: false, + removeComments: true, + noResolve: false, + stripInternal: false, + outFile: importDefinitelyTypedTestsJs + }, /*useBuiltCompiler*/ false); + return gulp.src(importDefinitelyTypedTestsTs) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")); +}); + +gulp.task("importDefinitelyTypedTests", "Runs scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts to copy DT's tests to the TS-internal RWC tests", [importDefinitelyTypedTestsJs], (done) => { + exec(host, [importDefinitelyTypedTestsJs, "./", "../DefinitelyTyped"], done, done); +}); + +gulp.task("lib", "Builds the library targets", libraryTargets); + + +// Generate diagnostics +const processDiagnosticMessagesJs = path.join(scriptsDirectory, "processDiagnosticMessages.js"); +const processDiagnosticMessagesTs = path.join(scriptsDirectory, "processDiagnosticMessages.ts"); +const diagnosticMessagesJson = path.join(compilerDirectory, "diagnosticMessages.json"); +const diagnosticInfoMapTs = path.join(compilerDirectory, "diagnosticInformationMap.generated.ts"); +const generatedDiagnosticMessagesJSON = path.join(compilerDirectory, "diagnosticMessages.generated.json"); +const builtGeneratedDiagnosticMessagesJSON = path.join(builtLocalDirectory, "diagnosticMessages.generated.json"); + +// processDiagnosticMessages script +gulp.task(processDiagnosticMessagesJs, false, [], () => { + const settings: tsc.Settings = getCompilerSettings({ + declaration: false, + removeComments: true, + noResolve: false, + stripInternal: false, + outFile: processDiagnosticMessagesJs + }, /*useBuiltCompiler*/ false); + return gulp.src(processDiagnosticMessagesTs) + .pipe(newer(processDiagnosticMessagesJs)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")); +}); + +// The generated diagnostics map; built for the compiler and for the "generate-diagnostics" task +gulp.task(diagnosticInfoMapTs, [processDiagnosticMessagesJs], (done) => { + if (needsUpdate(diagnosticMessagesJson, [generatedDiagnosticMessagesJSON, diagnosticInfoMapTs])) { + exec(host, [processDiagnosticMessagesJs, diagnosticMessagesJson], done, done); + } + else { + done(); + } +}); + +gulp.task(builtGeneratedDiagnosticMessagesJSON, [diagnosticInfoMapTs], (done) => { + if (fs.existsSync(builtLocalDirectory) && needsUpdate(generatedDiagnosticMessagesJSON, builtGeneratedDiagnosticMessagesJSON)) { + fs.writeFileSync(builtGeneratedDiagnosticMessagesJSON, fs.readFileSync(generatedDiagnosticMessagesJSON)); + } + done(); +}); + +gulp.task("generate-diagnostics", "Generates a diagnostic file in TypeScript based on an input JSON file", [diagnosticInfoMapTs]); + + +const servicesFile = path.join(builtLocalDirectory, "typescriptServices.js"); +const standaloneDefinitionsFile = path.join(builtLocalDirectory, "typescriptServices.d.ts"); +const nodePackageFile = path.join(builtLocalDirectory, "typescript.js"); +const nodeDefinitionsFile = path.join(builtLocalDirectory, "typescript.d.ts"); +const nodeStandaloneDefinitionsFile = path.join(builtLocalDirectory, "typescript_standalone.d.ts"); + +let copyrightContent: string; +function prependCopyright(outputCopyright: boolean = !useDebugMode) { + return insert.prepend(outputCopyright ? (copyrightContent || (copyrightContent = fs.readFileSync(copyright).toString())) : ""); +} + +gulp.task(builtLocalCompiler, false, [servicesFile], () => { + const localCompilerProject = tsc.createProject("src/compiler/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/true)); + return localCompilerProject.src() + .pipe(newer(builtLocalCompiler)) + .pipe(sourcemaps.init()) + .pipe(tsc(localCompilerProject)) + .pipe(prependCopyright()) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(builtLocalDirectory)); +}); + +gulp.task(servicesFile, false, ["lib", "generate-diagnostics"], () => { + const servicesProject = tsc.createProject("src/services/tsconfig.json", getCompilerSettings({ removeComments: false }, /*useBuiltCompiler*/false)); + const {js, dts} = servicesProject.src() + .pipe(newer(servicesFile)) + .pipe(sourcemaps.init()) + .pipe(tsc(servicesProject)); + const completedJs = js.pipe(prependCopyright()) + .pipe(sourcemaps.write(".")); + const completedDts = dts.pipe(prependCopyright(/*outputCopyright*/true)) + .pipe(insert.transform((contents, file) => { + file.path = standaloneDefinitionsFile; + return contents.replace(/^(\s*)(export )?const enum (\S+) {(\s*)$/gm, "$1$2enum $3 {$4"); + })); + return merge2([ + completedJs, + completedJs.pipe(clone()) + .pipe(insert.transform((content, file) => (file.path = nodePackageFile, content))), + completedDts, + completedDts.pipe(clone()) + .pipe(insert.transform((content, file) => { + file.path = nodeDefinitionsFile; + return content + "\r\nexport = ts;"; + })) + .pipe(gulp.dest(builtLocalDirectory)), + completedDts.pipe(clone()) + .pipe(insert.transform((content, file) => { + file.path = nodeStandaloneDefinitionsFile; + return content.replace(/declare (namespace|module) ts/g, 'declare module "typescript"'); + })) + ]).pipe(gulp.dest(builtLocalDirectory)); +}); + +const serverFile = path.join(builtLocalDirectory, "tsserver.js"); + +gulp.task(serverFile, false, [servicesFile], () => { + const serverProject = tsc.createProject("src/server/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/true)); + return serverProject.src() + .pipe(newer(serverFile)) + .pipe(sourcemaps.init()) + .pipe(tsc(serverProject)) + .pipe(prependCopyright()) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(builtLocalDirectory)); +}); + +const tsserverLibraryFile = path.join(builtLocalDirectory, "tsserverlibrary.js"); +const tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverlibrary.d.ts"); + +gulp.task(tsserverLibraryFile, false, [servicesFile], (done) => { + const settings: tsc.Settings = getCompilerSettings({ + declaration: true, + outFile: tsserverLibraryFile + }, /*useBuiltCompiler*/ true); + const {js, dts}: {js: NodeJS.ReadableStream, dts: NodeJS.ReadableStream} = gulp.src(languageServiceLibrarySources) + .pipe(sourcemaps.init()) + .pipe(newer(tsserverLibraryFile)) + .pipe(tsc(settings)); + + return merge2([ + js.pipe(prependCopyright()) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")), + dts.pipe(prependCopyright()) + .pipe(gulp.dest(".")) + ]); +}); + +gulp.task("lssl", "Builds language service server library", [tsserverLibraryFile]); +gulp.task("local", "Builds the full compiler and services", [builtLocalCompiler, servicesFile, serverFile, builtGeneratedDiagnosticMessagesJSON]); +gulp.task("tsc", "Builds only the compiler", [builtLocalCompiler]); + + +// Generate Markdown spec +const word2mdJs = path.join(scriptsDirectory, "word2md.js"); +const word2mdTs = path.join(scriptsDirectory, "word2md.ts"); +const specWord = path.join(docDirectory, "TypeScript Language Specification.docx"); +const specMd = path.join(docDirectory, "spec.md"); + +gulp.task(word2mdJs, false, [], () => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: word2mdJs + }, /*useBuiltCompiler*/ false); + return gulp.src(word2mdTs) + .pipe(newer(word2mdJs)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")); +}); + +gulp.task(specMd, false, [word2mdJs], (done) => { + const specWordFullPath = path.resolve(specWord); + const specMDFullPath = path.resolve(specMd); + const cmd = "cscript //nologo " + word2mdJs + " \"" + specWordFullPath + "\" " + "\"" + specMDFullPath + "\""; + console.log(cmd); + cp.exec(cmd, function () { + done(); + }); +}); + +gulp.task("generate-spec", "Generates a Markdown version of the Language Specification", [specMd]); + +gulp.task("clean", "Cleans the compiler output, declare files, and tests", [], () => { + return del([builtDirectory]); +}); + +gulp.task("useDebugMode", false, [], (done) => { useDebugMode = true; done(); }); +gulp.task("dontUseDebugMode", false, [], (done) => { useDebugMode = false; done(); }); + +gulp.task("VerifyLKG", false, [], () => { + const expectedFiles = [builtLocalCompiler, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile].concat(libraryTargets); + const missingFiles = expectedFiles.filter(function (f) { + return !fs.existsSync(f); + }); + if (missingFiles.length > 0) { + throw new Error("Cannot replace the LKG unless all built targets are present in directory " + builtLocalDirectory + + ". The following files are missing:\n" + missingFiles.join("\n")); + } + // Copy all the targets into the LKG directory + return gulp.src(expectedFiles).pipe(gulp.dest(LKGDirectory)); +}); + +gulp.task("LKGInternal", false, ["lib", "local", "lssl"]); + +gulp.task("LKG", "Makes a new LKG out of the built js files", ["clean", "dontUseDebugMode"], () => { + return runSequence("LKGInternal", "VerifyLKG"); +}); + + +// Task to build the tests infrastructure using the built compiler +const run = path.join(builtLocalDirectory, "run.js"); +gulp.task(run, false, [servicesFile], () => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: run + }, /*useBuiltCompiler*/ true); + return gulp.src(harnessSources) + .pipe(newer(run)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".", { includeContent: false, sourceRoot: "../../" })) + .pipe(gulp.dest(".")); +}); + +const internalTests = "internal/"; + +const localBaseline = "tests/baselines/local/"; +const refBaseline = "tests/baselines/reference/"; + +const localRwcBaseline = path.join(internalTests, "baselines/rwc/local"); +const refRwcBaseline = path.join(internalTests, "baselines/rwc/reference"); + +const localTest262Baseline = path.join(internalTests, "baselines/test262/local"); +const refTest262Baseline = path.join(internalTests, "baselines/test262/reference"); + + +gulp.task("tests", "Builds the test infrastructure using the built compiler", [run]); +gulp.task("tests-debug", "Builds the test sources and automation in debug mode", () => { + return runSequence("useDebugMode", "tests"); +}); + +function deleteTemporaryProjectOutput() { + return del(path.join(localBaseline, "projectOutput/")); +} + +let savedNodeEnv: string; +function setNodeEnvToDevelopment() { + savedNodeEnv = process.env.NODE_ENV; + process.env.NODE_ENV = "development"; +} + +function restoreSavedNodeEnv() { + process.env.NODE_ENV = savedNodeEnv; +} + +let testTimeout = 20000; +function runConsoleTests(defaultReporter: string, runInParallel: boolean, done: (e?: any) => void) { + const lintFlag = cmdLineOptions["lint"]; + cleanTestDirs((err) => { + if (err) { console.error(err); failWithStatus(err, 1); } + const debug = cmdLineOptions["debug"]; + const tests = cmdLineOptions["tests"]; + const light = cmdLineOptions["light"]; + const testConfigFile = "test.config"; + if (fs.existsSync(testConfigFile)) { + fs.unlinkSync(testConfigFile); + } + let workerCount, taskConfigsFolder; + if (runInParallel) { + // generate name to store task configuration files + const prefix = os.tmpdir() + "/ts-tests"; + let i = 1; + do { + taskConfigsFolder = prefix + i; + i++; + } while (fs.existsSync(taskConfigsFolder)); + fs.mkdirSync(taskConfigsFolder); + + workerCount = process.env.workerCount || os.cpus().length; + } + + if (tests || light || taskConfigsFolder) { + writeTestConfigFile(tests, light, taskConfigsFolder, workerCount); + } + + if (tests && tests.toLocaleLowerCase() === "rwc") { + testTimeout = 100000; + } + + const colors = cmdLineOptions["colors"]; + const reporter = cmdLineOptions["reporter"] || defaultReporter; + + // timeout normally isn"t necessary but Travis-CI has been timing out on compiler baselines occasionally + // default timeout is 2sec which really should be enough, but maybe we just need a small amount longer + if (!runInParallel) { + const args = []; + if (debug) { + args.push("--debug-brk"); + } + args.push("-R", reporter); + if (tests) { + args.push("-g", `"${tests}"`); + } + if (colors) { + args.push("--colors"); + } + else { + args.push("--no-colors"); + } + args.push("-t", testTimeout); + args.push(run); + setNodeEnvToDevelopment(); + exec(mocha, args, lintThenFinish, function(e, status) { + finish(e, status); + }); + + } + else { + // run task to load all tests and partition them between workers + const args = []; + args.push("-R", "min"); + if (colors) { + args.push("--colors"); + } + else { + args.push("--no-colors"); + } + args.push(run); + setNodeEnvToDevelopment(); + runTestsInParallel(taskConfigsFolder, run, { testTimeout: testTimeout, noColors: colors === " --no-colors " }, function (err) { + // last worker clean everything and runs linter in case if there were no errors + del(taskConfigsFolder).then(() => { + if (!err) { + lintThenFinish(); + } + else { + finish(err); + } + }); + }); + } + }); + + function failWithStatus(err?: any, status?: number) { + if (err) { + console.log(err); + } + done(err || status); + process.exit(status); + } + + function lintThenFinish() { + if (lintFlag) { + runSequence("lint", finish); + } + else { + finish(); + } + } + + function finish(error?: any, errorStatus?: number) { + restoreSavedNodeEnv(); + deleteTemporaryProjectOutput().then(() => { + if (error !== undefined || errorStatus !== undefined) { + failWithStatus(error, errorStatus); + } + else { + done(); + } + }); + } +} + +gulp.task("runtests-parallel", "Runs all the tests in parallel using the built run.js file. Optional arguments are: --t[ests]=category1|category2|... --d[ebug]=true.", ["build-rules", "tests"], (done) => { + runConsoleTests("min", /*runInParallel*/ true, done); +}); +gulp.task("runtests", + "Runs the tests using the built run.js file. Optional arguments are: --t[ests]=regex --r[eporter]=[list|spec|json|] --d[ebug]=true --color[s]=false --lint=true.", + ["build-rules", "tests"], + (done) => { + runConsoleTests("mocha-fivemat-progress-reporter", /*runInParallel*/ false, done); +}); + +const nodeServerOutFile = "tests/webTestServer.js"; +const nodeServerInFile = "tests/webTestServer.ts"; +gulp.task(nodeServerOutFile, false, [servicesFile], () => { + const settings: tsc.Settings = getCompilerSettings({ module: "commonjs" }, /*useBuiltCompiler*/ true); + return gulp.src(nodeServerInFile) + .pipe(newer(nodeServerOutFile)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(path.dirname(nodeServerOutFile))); +}); + +gulp.task("browserify", "Runs browserify on run.js to produce a file suitable for running tests in the browser", [servicesFile], (done) => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: "built/local/bundle.js" + }, /*useBuiltCompiler*/ true); + return gulp.src(harnessSources) + .pipe(newer("built/local/bundle.js")) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(through2.obj((file, enc, next) => { + browserify(intoStream(file.contents)) + .bundle((err, res) => { + // assumes file.contents is a Buffer + file.contents = res; + next(undefined, file); + }); + })) + .pipe(sourcemaps.write(".", { includeContent: false, sourceRoot: "../../" })) + .pipe(gulp.dest(".")); +}); + + +function cleanTestDirs(done: (e?: any) => void) { + // Clean the local baselines & Rwc baselines directories + del([ + localBaseline, + localRwcBaseline, + ]).then(() => { + mkdirP(localRwcBaseline, (err) => { + if (err) done(err); + mkdirP(localTest262Baseline, () => { + if (err) done(err); + mkdirP(localBaseline, (err) => done(err)); + }); + }); + }); +} + +// used to pass data from jake command line directly to run.js +function writeTestConfigFile(tests: string, light: boolean, taskConfigsFolder?: string, workerCount?: number) { + const testConfigContents = JSON.stringify({ test: tests ? [tests] : undefined, light: light, workerCount: workerCount, taskConfigsFolder: taskConfigsFolder }); + console.log("Running tests with config: " + testConfigContents); + fs.writeFileSync("test.config", testConfigContents); +} + + +gulp.task("runtests-browser", "Runs the tests using the built run.js file like 'gulp runtests'. Syntax is gulp runtests-browser. Additional optional parameters --tests=[regex], --port=, --browser=[chrome|IE]", ["browserify", nodeServerOutFile], (done) => { + cleanTestDirs((err) => { + if (err) { console.error(err); done(err); process.exit(1); } + host = "node"; + const tests = cmdLineOptions["tests"]; + const light = cmdLineOptions["light"]; + const testConfigFile = "test.config"; + if (fs.existsSync(testConfigFile)) { + fs.unlinkSync(testConfigFile); + } + if (tests || light) { + writeTestConfigFile(tests, light); + } + + const args = [nodeServerOutFile]; + if (cmdLineOptions["port"]) { + args.push(cmdLineOptions["port"]); + } + if (cmdLineOptions["browser"]) { + args.push(cmdLineOptions["browser"]); + } + if (tests) { + args.push(JSON.stringify(tests)); + } + exec(host, args, done, done); + }); +}); + +gulp.task("generate-code-coverage", "Generates code coverage data via istanbul", ["tests"], (done) => { + exec("istanbul", ["cover", "node_modules/mocha/bin/_mocha", "--", "-R", "min", "-t", testTimeout.toString(), run], done, done); +}); + + +function getDiffTool() { + const program = process.env["DIFF"]; + if (!program) { + console.error("Add the 'DIFF' environment variable to the path of the program you want to use."); + process.exit(1); + } + return program; +} + +gulp.task("diff", "Diffs the compiler baselines using the diff tool specified by the 'DIFF' environment variable", (done) => { + exec(getDiffTool(), [refBaseline, localBaseline], done, done); +}); +gulp.task("diff-rwc", "Diffs the RWC baselines using the diff tool specified by the 'DIFF' environment variable", (done) => { + exec(getDiffTool(), [refRwcBaseline, localRwcBaseline], done, done); +}); + + +gulp.task("baseline-accept", "Makes the most recent test results the new baseline, overwriting the old baseline", (done) => { + const softAccept = cmdLineOptions["soft"]; + if (!softAccept) { + del(refBaseline).then(() => { + fs.renameSync(localBaseline, refBaseline); + done(); + }, done); + } + else { + gulp.src(localBaseline) + .pipe(gulp.dest(refBaseline)) + .on("end", () => { + del(path.join(refBaseline, "local")).then(() => done(), done); + }); + } +}); +gulp.task("baseline-accept-rwc", "Makes the most recent rwc test results the new baseline, overwriting the old baseline", () => { + return del(refRwcBaseline).then(() => { + fs.renameSync(localRwcBaseline, refRwcBaseline); + }); +}); +gulp.task("baseline-accept-test262", "Makes the most recent test262 test results the new baseline, overwriting the old baseline", () => { + return del(refTest262Baseline).then(() => { + fs.renameSync(localTest262Baseline, refTest262Baseline); + }); +}); + + +// Webhost +const webhostPath = "tests/webhost/webtsc.ts"; +const webhostJsPath = "tests/webhost/webtsc.js"; +gulp.task(webhostJsPath, false, [servicesFile], () => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: webhostJsPath + }, /*useBuiltCompiler*/ true); + return gulp.src(webhostPath) + .pipe(newer(webhostJsPath)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(path.dirname(webhostJsPath))); +}); + +gulp.task("webhost", "Builds the tsc web host", [webhostJsPath], () => { + return gulp.src(path.join(builtLocalDirectory, "lib.d.ts")).pipe(gulp.dest("tests/webhost/")); +}); + + +// Perf compiler +const perftscPath = "tests/perftsc.ts"; +const perftscJsPath = "built/local/perftsc.js"; +gulp.task(perftscJsPath, false, [servicesFile], () => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: perftscJsPath + }, /*useBuiltCompiler*/ true); + return gulp.src(perftscPath) + .pipe(newer(perftscJsPath)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")); +}); + +gulp.task("perftsc", "Builds augmented version of the compiler for perf tests", [perftscJsPath]); + + +// Instrumented compiler +const loggedIOpath = path.join(harnessDirectory, "loggedIO.ts"); +const loggedIOJsPath = path.join(builtLocalDirectory, "loggedIO.js"); +gulp.task(loggedIOJsPath, false, [], (done) => { + const temp = path.join(builtLocalDirectory, "temp"); + mkdirP(temp, (err) => { + if (err) { console.error(err); done(err); process.exit(1); }; + exec(host, [LKGCompiler, "--outdir", temp, loggedIOpath], () => { + fs.renameSync(path.join(temp, "/harness/loggedIO.js"), loggedIOJsPath); + del(temp).then(() => done(), done); + }, done); + }); +}); + +const instrumenterPath = path.join(harnessDirectory, "instrumenter.ts"); +const instrumenterJsPath = path.join(builtLocalDirectory, "instrumenter.js"); +gulp.task(instrumenterJsPath, false, [servicesFile], () => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: instrumenterJsPath + }, /*useBuiltCompiler*/ true); + return gulp.src(instrumenterPath) + .pipe(newer(instrumenterJsPath)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")); +}); + +gulp.task("tsc-instrumented", "Builds an instrumented tsc.js", [loggedIOJsPath, instrumenterJsPath, servicesFile], (done) => { + exec(host, [instrumenterJsPath, "record", "iocapture", builtLocalDirectory, compilerFilename], done, done); +}); + +gulp.task("update-sublime", "Updates the sublime plugin's tsserver", ["local", serverFile], () => { + return gulp.src([serverFile, serverFile + ".map"]).pipe(gulp.dest("../TypeScript-Sublime-Plugin/tsserver/")); +}); + + +const tslintRuleDir = "scripts/tslint"; +const tslintRules = [ + "nextLineRule", + "preferConstRule", + "booleanTriviaRule", + "typeOperatorSpacingRule", + "noInOperatorRule", + "noIncrementDecrementRule", + "objectLiteralSurroundingSpaceRule", +]; +const tslintRulesFiles = tslintRules.map(function(p) { + return path.join(tslintRuleDir, p + ".ts"); +}); +const tslintRulesOutFiles = tslintRules.map(function(p, i) { + const pathname = path.join(builtLocalDirectory, "tslint", p + ".js"); + gulp.task(pathname, false, [], () => { + const settings: tsc.Settings = getCompilerSettings({ module: "commonjs" }, /*useBuiltCompiler*/ false); + return gulp.src(tslintRulesFiles[i]) + .pipe(newer(pathname)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(path.join(builtLocalDirectory, "tslint"))); + }); + return pathname; +}); + +gulp.task("build-rules", "Compiles tslint rules to js", tslintRulesOutFiles); + + +function getLinterOptions() { + return { + configuration: require("./tslint.json"), + formatter: "prose", + formattersDirectory: undefined, + rulesDirectory: "built/local/tslint" + }; +} + +function lintFileContents(options, path, contents) { + const ll = new Linter(path, contents, options); + console.log("Linting '" + path + "'."); + return ll.lint(); +} + +function lintFile(options, path) { + const contents = fs.readFileSync(path, "utf8"); + return lintFileContents(options, path, contents); +} + +const lintTargets = ["Gulpfile.ts"] + .concat(compilerSources) + .concat(harnessSources) + // Other harness sources + .concat(["instrumenter.ts"].map(function(f) { return path.join(harnessDirectory, f); })) + .concat(serverCoreSources) + .concat(tslintRulesFiles) + .concat(servicesSources); + + +gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are: --f[iles]=regex", ["build-rules"], () => { + const lintOptions = getLinterOptions(); + let failed = 0; + const fileMatcher = RegExp(cmdLineOptions["files"]); + const done = {}; + for (const i in lintTargets) { + const target = lintTargets[i]; + if (!done[target] && fileMatcher.test(target)) { + const result = lintFile(lintOptions, target); + if (result.failureCount > 0) { + console.log(result.output); + failed += result.failureCount; + } + done[target] = true; + } + } + if (failed > 0) { + console.error("Linter errors."); + process.exit(1); + } +}); + + +gulp.task("default", "Runs 'local'", ["local"]); + +gulp.task("watch", "Watches the src/ directory for changes and executes runtests-parallel.", [], () => { + gulp.watch("src/**/*.*", ["runtests-parallel"]); +}); diff --git a/Jakefile.js b/Jakefile.js index f11d1bf423d..7db91abcfcc 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -284,7 +284,7 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename); function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts, callback) { file(outFile, prereqs, function() { var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler; - var options = "--noImplicitAny --noEmitOnError --pretty"; + var options = "--noImplicitAny --noEmitOnError --types --pretty"; opts = opts || {}; // Keep comments when specifically requested // or when in debug mode. @@ -992,7 +992,8 @@ var tslintRules = [ "booleanTriviaRule", "typeOperatorSpacingRule", "noInOperatorRule", - "noIncrementDecrementRule" + "noIncrementDecrementRule", + "objectLiteralSurroundingSpaceRule", ]; var tslintRulesFiles = tslintRules.map(function(p) { return path.join(tslintRuleDir, p + ".ts"); @@ -1043,7 +1044,8 @@ var lintTargets = compilerSources .concat(["instrumenter.ts"].map(function(f) { return path.join(harnessDirectory, f) })) .concat(serverCoreSources) .concat(tslintRulesFiles) - .concat(servicesSources); + .concat(servicesSources) + .concat(["Gulpfile.ts"]); desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex"); diff --git a/README.md b/README.md index 13e1f3e4786..fca2890bc77 100644 --- a/README.md +++ b/README.md @@ -56,29 +56,29 @@ Change to the TypeScript directory: cd TypeScript ``` -Install Jake tools and dev dependencies: +Install Gulp tools and dev dependencies: ``` -npm install -g jake +npm install -g gulp npm install ``` Use one of the following to build and test: ``` -jake local # Build the compiler into built/local -jake clean # Delete the built compiler -jake LKG # Replace the last known good with the built one. +gulp local # Build the compiler into built/local +gulp clean # Delete the built compiler +gulp LKG # Replace the last known good with the built one. # Bootstrapping step to be executed when the built compiler reaches a stable state. -jake tests # Build the test infrastructure using the built compiler. -jake runtests # Run tests using the built compiler and test infrastructure. +gulp tests # Build the test infrastructure using the built compiler. +gulp runtests # Run tests using the built compiler and test infrastructure. # You can override the host or specify a test for this command. # Use host= or tests=. -jake runtests-browser # Runs the tests using the built run.js file. Syntax is jake runtests. Optional +gulp runtests-browser # Runs the tests using the built run.js file. Syntax is gulp runtests. Optional parameters 'host=', 'tests=[regex], reporter=[list|spec|json|]'. -jake baseline-accept # This replaces the baseline test results with the results obtained from jake runtests. -jake lint # Runs tslint on the TypeScript source. -jake -T # List the above commands. +gulp baseline-accept # This replaces the baseline test results with the results obtained from gulp runtests. +gulp lint # Runs tslint on the TypeScript source. +gulp help # List the above commands. ``` diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 2881834e678..e25105cc98e 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -1271,13 +1271,33 @@ declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | P interface PromiseLike { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): PromiseLike; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): PromiseLike; } interface ArrayLike { @@ -1540,7 +1560,7 @@ interface Int8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -1813,7 +1833,7 @@ interface Uint8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2087,7 +2107,7 @@ interface Uint8ClampedArray { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2360,7 +2380,7 @@ interface Int16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2634,7 +2654,7 @@ interface Uint16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2907,7 +2927,7 @@ interface Int32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3180,7 +3200,7 @@ interface Uint32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3453,7 +3473,7 @@ interface Float32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3727,7 +3747,7 @@ interface Float64Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -4126,7 +4146,7 @@ interface Date { ///////////////////////////// interface Algorithm { - name?: string; + name: string; } interface AriaRequestEventInit extends EventInit { @@ -4973,6 +4993,7 @@ interface UIEventInit extends EventInit { } interface WebGLContextAttributes { + failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; depth?: boolean; stencil?: boolean; @@ -5041,7 +5062,7 @@ interface ApplicationCache extends EventTarget { oncached: (ev: Event) => any; onchecking: (ev: Event) => any; ondownloading: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onnoupdate: (ev: Event) => any; onobsolete: (ev: Event) => any; onprogress: (ev: ProgressEvent) => any; @@ -6411,7 +6432,7 @@ declare var DeviceRotationRate: { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent { /** - * Sets or gets the URL for the current document. + * Sets or gets the URL for the current document. */ readonly URL: string; /** @@ -6439,7 +6460,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ bgColor: string; /** @@ -6467,19 +6488,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. + * Sets or retrieves a value that indicates the reading order of the object. */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. + * Gets an object representing the document type declaration associated with the current document. */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. + * Gets a reference to the root node of the document. */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. + * Sets or gets the security domain of the document. */ domain: string; /** @@ -6503,7 +6524,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. + * Gets the implementation object of the current document. */ readonly implementation: DOMImplementation; /** @@ -6511,11 +6532,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. + * Gets the date that the page was last modified, if the page supplies one. */ readonly lastModified: string; /** - * Sets or gets the color of the document links. + * Sets or gets the color of the document links. */ linkColor: string; /** @@ -6523,7 +6544,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ links: HTMLCollectionOf; /** - * Contains information about the current URL. + * Contains information about the current URL. */ readonly location: Location; msCSSOMElementFloatMetrics: boolean; @@ -6532,7 +6553,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when the user aborts the download. * @param ev The event. */ - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; /** * Fires when the object is set as the active element. * @param ev The event. @@ -6548,19 +6569,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ onbeforedeactivate: (ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. + /** + * Fires when the object loses the input focus. * @param ev The focus event. */ onblur: (ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. + * Occurs when playback is possible, but would require further buffering. * @param ev The event. */ oncanplay: (ev: Event) => any; oncanplaythrough: (ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. + * Fires when the contents of the object or selection have changed. * @param ev The event. */ onchange: (ev: Event) => any; @@ -6570,7 +6591,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onclick: (ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * Fires when the user clicks the right mouse button in the client area, opening the context menu. * @param ev The mouse event. */ oncontextmenu: (ev: PointerEvent) => any; @@ -6594,12 +6615,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ ondragend: (ev: DragEvent) => any; - /** + /** * Fires on the target element when the user drags the object to a valid drop target. * @param ev The drag event. */ ondragenter: (ev: DragEvent) => any; - /** + /** * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. * @param ev The drag event. */ @@ -6610,23 +6631,23 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ ondragover: (ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. + * Fires on the source object when the user starts to drag a text selection or selected object. * @param ev The event. */ ondragstart: (ev: DragEvent) => any; ondrop: (ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. + * Occurs when the duration attribute is updated. * @param ev The event. */ ondurationchange: (ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. + * Occurs when the media element is reset to its initial state. * @param ev The event. */ onemptied: (ev: Event) => any; /** - * Occurs when the end of playback is reached. + * Occurs when the end of playback is reached. * @param ev The event */ onended: (ev: MediaStreamErrorEvent) => any; @@ -6634,9 +6655,9 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** - * Fires when the object receives focus. + * Fires when the object receives focus. * @param ev The event. */ onfocus: (ev: FocusEvent) => any; @@ -6660,12 +6681,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onkeyup: (ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. + * Fires immediately after the browser loads the object. * @param ev The event. */ onload: (ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. + * Occurs when media data is loaded at the current playback position. * @param ev The event. */ onloadeddata: (ev: Event) => any; @@ -6675,22 +6696,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onloadedmetadata: (ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. + * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ onloadstart: (ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. + * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ onmousedown: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. + * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ onmousemove: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. + * Fires when the user moves the mouse pointer outside the boundaries of the object. * @param ev The mouse event. */ onmouseout: (ev: MouseEvent) => any; @@ -6700,12 +6721,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onmouseover: (ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. + * Fires when the user releases a mouse button while the mouse is over the object. * @param ev The mouse event. */ onmouseup: (ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. + * Fires when the wheel button is rotated. * @param ev The mouse event */ onmousewheel: (ev: WheelEvent) => any; @@ -6727,7 +6748,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (ev: MSPointerEvent) => any; onmspointerup: (ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. * @param ev The event. */ onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; @@ -6742,24 +6763,24 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onpause: (ev: Event) => any; /** - * Occurs when the play method is requested. + * Occurs when the play method is requested. * @param ev The event. */ onplay: (ev: Event) => any; /** - * Occurs when the audio or video has started playing. + * Occurs when the audio or video has started playing. * @param ev The event. */ onplaying: (ev: Event) => any; onpointerlockchange: (ev: Event) => any; onpointerlockerror: (ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. + * Occurs to indicate progress while downloading media data. * @param ev The event. */ onprogress: (ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. + * Occurs when the playback rate is increased or decreased. * @param ev The event. */ onratechange: (ev: Event) => any; @@ -6769,22 +6790,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onreadystatechange: (ev: ProgressEvent) => any; /** - * Fires when the user resets a form. + * Fires when the user resets a form. * @param ev The event. */ onreset: (ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. + * Fires when the user repositions the scroll box in the scroll bar on the object. * @param ev The event. */ onscroll: (ev: UIEvent) => any; /** - * Occurs when the seek operation ends. + * Occurs when the seek operation ends. * @param ev The event. */ onseeked: (ev: Event) => any; /** - * Occurs when the current playback position is moved. + * Occurs when the current playback position is moved. * @param ev The event. */ onseeking: (ev: Event) => any; @@ -6800,7 +6821,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onselectionchange: (ev: Event) => any; onselectstart: (ev: Event) => any; /** - * Occurs when the download has stopped. + * Occurs when the download has stopped. * @param ev The event. */ onstalled: (ev: Event) => any; @@ -6811,7 +6832,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onstop: (ev: Event) => any; onsubmit: (ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. + * Occurs if the load operation has been intentionally halted. * @param ev The event. */ onsuspend: (ev: Event) => any; @@ -6830,7 +6851,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onvolumechange: (ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. + * Occurs when playback stops because the next frame of a video resource is not available. * @param ev The event. */ onwaiting: (ev: Event) => any; @@ -6864,7 +6885,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ title: string; readonly visibilityState: string; - /** + /** * Sets or gets the color of the links that the user has visited. */ vlinkColor: string; @@ -7054,7 +7075,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. * @param root The root element or node to start traversing on. * @param whatToShow The type of nodes or elements to appear in the node list * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. @@ -7063,11 +7084,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. */ createRange(): Range; /** - * Creates a text string from the specified value. + * Creates a text string from the specified value. * @param data String that specifies the nodeValue property of the text node. */ createTextNode(data: string): Text; @@ -7082,7 +7103,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. + * Returns the element for the specified x coordinate and the specified y coordinate. * @param x The x-offset * @param y The y-offset */ @@ -7110,7 +7131,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Returns a reference to the first object with the specified value of the ID or NAME attribute. * @param elementId String that specifies the ID value. Case-insensitive. */ - getElementById(elementId: string): HTMLElement; + getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** * Gets a collection of objects based on the value of the NAME or ID attribute. @@ -7320,7 +7341,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param replace Specifies whether the existing entry for the document is replaced in the history list. */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** + /** * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. * @param commandId Specifies a command identifier. */ @@ -7342,7 +7363,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven queryCommandSupported(commandId: string): boolean; /** * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. */ queryCommandText(commandId: string): string; /** @@ -7358,12 +7379,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. + * Writes one or more HTML expressions to a document in the specified window. * @param content Specifies the text and HTML tags to write. */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; @@ -7585,7 +7606,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec readonly scrollWidth: number; readonly tagName: string; innerHTML: string; - getAttribute(name?: string): string | null; + getAttribute(name: string): string | null; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; @@ -7795,6 +7816,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: string): Element | null; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -8091,12 +8113,12 @@ interface HTMLAnchorElement extends HTMLElement { */ target: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; type: string; urn: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -8198,7 +8220,7 @@ interface HTMLAreaElement extends HTMLElement { */ host: string; /** - * Sets or retrieves the host name part of the location or URL. + * Sets or retrieves the host name part of the location or URL. */ hostname: string; /** @@ -8234,7 +8256,7 @@ interface HTMLAreaElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -8325,7 +8347,7 @@ interface HTMLBodyElement extends HTMLElement { onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; onhashchange: (ev: HashChangeEvent) => any; onload: (ev: Event) => any; @@ -8500,7 +8522,7 @@ interface HTMLButtonElement extends HTMLElement { * Overrides the target attribute on a form element. */ formTarget: string; - /** + /** * Sets or retrieves the name of the object. */ name: string; @@ -8517,7 +8539,7 @@ interface HTMLButtonElement extends HTMLElement { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; - /** + /** * Sets or retrieves the default or selected value of the control. */ value: string; @@ -8554,9 +8576,9 @@ interface HTMLCanvasElement extends HTMLElement { * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); */ - getContext(contextId: "2d"): CanvasRenderingContext2D; - getContext(contextId: "experimental-webgl"): WebGLRenderingContext; - getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext; + getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; + getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; + getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ @@ -8566,7 +8588,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; - toBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, ... arguments: any[]): void; } declare var HTMLCanvasElement: { @@ -8624,7 +8646,7 @@ declare var HTMLDirectoryElement: { interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; /** @@ -8664,7 +8686,7 @@ interface HTMLElement extends Element { readonly offsetParent: Element; readonly offsetTop: number; readonly offsetWidth: number; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onactivate: (ev: UIEvent) => any; onbeforeactivate: (ev: UIEvent) => any; onbeforecopy: (ev: ClipboardEvent) => any; @@ -8692,7 +8714,7 @@ interface HTMLElement extends Element { ondurationchange: (ev: Event) => any; onemptied: (ev: Event) => any; onended: (ev: MediaStreamErrorEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; oninput: (ev: Event) => any; oninvalid: (ev: Event) => any; @@ -9242,7 +9264,7 @@ interface HTMLFrameSetElement extends HTMLElement { * Fires when the object loses the input focus. */ onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** * Fires when the object receives focus. */ @@ -9765,9 +9787,9 @@ interface HTMLInputElement extends HTMLElement { /** * Returns a FileList object on a file type input object. */ - readonly files: FileList; + readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -10487,7 +10509,7 @@ interface HTMLMetaElement extends HTMLElement { */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; } @@ -10736,7 +10758,7 @@ declare var HTMLOptionElement: { create(): HTMLOptionElement; } -interface HTMLOptionsCollection extends HTMLCollection { +interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; @@ -10750,7 +10772,7 @@ declare var HTMLOptionsCollection: { interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; clear: string; @@ -10852,10 +10874,10 @@ interface HTMLScriptElement extends HTMLElement { */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. + * Sets or retrieves the event for which the script is written. */ event: string; - /** + /** * Sets or retrieves the object that is bound to the event script. */ htmlFor: string; @@ -10864,7 +10886,7 @@ interface HTMLScriptElement extends HTMLElement { */ src: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; /** @@ -10885,7 +10907,7 @@ interface HTMLSelectElement extends HTMLElement { autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -10900,7 +10922,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLCollectionOf; + readonly options: HTMLOptionsCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -10911,7 +10933,7 @@ interface HTMLSelectElement extends HTMLElement { selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. + * Sets or retrieves the number of rows in the list box. */ size: number; /** @@ -10937,7 +10959,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. */ add(element: HTMLElement, before?: HTMLElement | number): void; /** @@ -11132,7 +11154,7 @@ interface HTMLTableElement extends HTMLElement { */ border: string; /** - * Sets or retrieves the border color of the object. + * Sets or retrieves the border color of the object. */ borderColor: any; /** @@ -11427,7 +11449,7 @@ declare var HTMLTextAreaElement: { interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; } @@ -11696,7 +11718,7 @@ interface IDBDatabase extends EventTarget { readonly name: string; readonly objectStoreNames: DOMStringList; onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; version: number; onversionchange: (ev: IDBVersionChangeEvent) => any; close(): void; @@ -11799,7 +11821,7 @@ declare var IDBOpenDBRequest: { interface IDBRequest extends EventTarget { readonly error: DOMError; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onsuccess: (ev: Event) => any; readonly readyState: string; readonly result: any; @@ -11821,7 +11843,7 @@ interface IDBTransaction extends EventTarget { readonly mode: string; onabort: (ev: Event) => any; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -11964,7 +11986,7 @@ declare var MSApp: MSApp; interface MSAppAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; start(): void; @@ -12324,7 +12346,7 @@ declare var MSStreamReader: { interface MSWebViewAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; readonly target: MSHTMLWebViewElement; @@ -12860,7 +12882,7 @@ interface Node extends EventTarget { contains(child: Node): boolean; hasAttributes(): boolean; hasChildNodes(): boolean; - insertBefore(newChild: Node, refChild: Node): Node; + insertBefore(newChild: Node, refChild: Node | null): Node; isDefaultNamespace(namespaceURI: string | null): boolean; isEqualNode(arg: Node): boolean; isSameNode(other: Node): boolean; @@ -12869,7 +12891,6 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; - contains(node: Node): boolean; readonly ATTRIBUTE_NODE: number; readonly CDATA_SECTION_NODE: number; readonly COMMENT_NODE: number; @@ -13405,7 +13426,7 @@ declare var RTCDTMFToneChangeEvent: { interface RTCDtlsTransport extends RTCStatsProvider { ondtlsstatechange: ((ev: RTCDtlsTransportStateChangedEvent) => any) | null; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly state: string; readonly transport: RTCIceTransport; getLocalParameters(): RTCDtlsParameters; @@ -13460,7 +13481,7 @@ declare var RTCIceCandidatePairChangedEvent: { interface RTCIceGatherer extends RTCStatsProvider { readonly component: string; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onlocalcandidate: ((ev: RTCIceGathererEvent) => any) | null; createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidate[]; @@ -13519,7 +13540,7 @@ declare var RTCIceTransportStateChangedEvent: { } interface RTCRtpReceiver extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -13539,7 +13560,7 @@ declare var RTCRtpReceiver: { } interface RTCRtpSender extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onssrcconflict: ((ev: RTCSsrcConflictEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack; @@ -13560,7 +13581,7 @@ declare var RTCRtpSender: { } interface RTCSrtpSdesTransport extends EventTarget { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly transport: RTCIceTransport; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -15600,18 +15621,24 @@ declare var StyleSheetPageList: { } interface SubtleCrypto { - decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: string | Algorithm, data: ArrayBufferView): PromiseLike; - encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; } declare var SubtleCrypto: { @@ -15679,7 +15706,7 @@ interface TextTrack extends EventTarget { readonly language: string; mode: any; oncuechange: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; readonly readyState: number; addCue(cue: TextTrackCue): void; @@ -16168,18 +16195,12 @@ interface WebGLRenderingContext { stencilMaskSeparate(face: number, mask: number): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; - texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels?: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; texParameterf(target: number, pname: number, param: number): void; texParameteri(target: number, pname: number, param: number): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels?: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; uniform1f(location: WebGLUniformLocation | null, x: number): void; uniform1fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; uniform1i(location: WebGLUniformLocation | null, x: number): void; @@ -16902,7 +16923,7 @@ interface WebSocket extends EventTarget { readonly bufferedAmount: number; readonly extensions: string; onclose: (ev: CloseEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onmessage: (ev: MessageEvent) => any; onopen: (ev: Event) => any; readonly protocol: string; @@ -16977,7 +16998,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window name: string; readonly navigator: Navigator; offscreenBuffering: string | boolean; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onafterprint: (ev: Event) => any; onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -17093,6 +17114,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly top: Window; readonly window: Window; URL: typeof URL; + Blob: typeof Blob; alert(message?: any): void; blur(): void; cancelAnimationFrame(handle: number): void; @@ -17249,7 +17271,6 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - msCaching: string; onreadystatechange: (ev: ProgressEvent) => any; readonly readyState: number; readonly response: any; @@ -17261,6 +17282,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { timeout: number; readonly upload: XMLHttpRequestUpload; withCredentials: boolean; + msCaching?: string; abort(): void; getAllResponseHeaders(): string; getResponseHeader(header: string): string | null; @@ -17399,7 +17421,7 @@ declare var XSLTProcessor: { } interface AbstractWorker { - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -17558,7 +17580,7 @@ interface LinkStyle { interface MSBaseReader { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -17623,7 +17645,359 @@ interface NavigatorUserMedia { } interface NodeSelector { + querySelector(selectors: "a"): HTMLAnchorElement; + querySelector(selectors: "abbr"): HTMLElement; + querySelector(selectors: "acronym"): HTMLElement; + querySelector(selectors: "address"): HTMLElement; + querySelector(selectors: "applet"): HTMLAppletElement; + querySelector(selectors: "area"): HTMLAreaElement; + querySelector(selectors: "article"): HTMLElement; + querySelector(selectors: "aside"): HTMLElement; + querySelector(selectors: "audio"): HTMLAudioElement; + querySelector(selectors: "b"): HTMLElement; + querySelector(selectors: "base"): HTMLBaseElement; + querySelector(selectors: "basefont"): HTMLBaseFontElement; + querySelector(selectors: "bdo"): HTMLElement; + querySelector(selectors: "big"): HTMLElement; + querySelector(selectors: "blockquote"): HTMLQuoteElement; + querySelector(selectors: "body"): HTMLBodyElement; + querySelector(selectors: "br"): HTMLBRElement; + querySelector(selectors: "button"): HTMLButtonElement; + querySelector(selectors: "canvas"): HTMLCanvasElement; + querySelector(selectors: "caption"): HTMLTableCaptionElement; + querySelector(selectors: "center"): HTMLElement; + querySelector(selectors: "circle"): SVGCircleElement; + querySelector(selectors: "cite"): HTMLElement; + querySelector(selectors: "clippath"): SVGClipPathElement; + querySelector(selectors: "code"): HTMLElement; + querySelector(selectors: "col"): HTMLTableColElement; + querySelector(selectors: "colgroup"): HTMLTableColElement; + querySelector(selectors: "datalist"): HTMLDataListElement; + querySelector(selectors: "dd"): HTMLElement; + querySelector(selectors: "defs"): SVGDefsElement; + querySelector(selectors: "del"): HTMLModElement; + querySelector(selectors: "desc"): SVGDescElement; + querySelector(selectors: "dfn"): HTMLElement; + querySelector(selectors: "dir"): HTMLDirectoryElement; + querySelector(selectors: "div"): HTMLDivElement; + querySelector(selectors: "dl"): HTMLDListElement; + querySelector(selectors: "dt"): HTMLElement; + querySelector(selectors: "ellipse"): SVGEllipseElement; + querySelector(selectors: "em"): HTMLElement; + querySelector(selectors: "embed"): HTMLEmbedElement; + querySelector(selectors: "feblend"): SVGFEBlendElement; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; + querySelector(selectors: "fecomposite"): SVGFECompositeElement; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; + querySelector(selectors: "feflood"): SVGFEFloodElement; + querySelector(selectors: "fefunca"): SVGFEFuncAElement; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; + querySelector(selectors: "feimage"): SVGFEImageElement; + querySelector(selectors: "femerge"): SVGFEMergeElement; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement; + querySelector(selectors: "feoffset"): SVGFEOffsetElement; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement; + querySelector(selectors: "fetile"): SVGFETileElement; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; + querySelector(selectors: "fieldset"): HTMLFieldSetElement; + querySelector(selectors: "figcaption"): HTMLElement; + querySelector(selectors: "figure"): HTMLElement; + querySelector(selectors: "filter"): SVGFilterElement; + querySelector(selectors: "font"): HTMLFontElement; + querySelector(selectors: "footer"): HTMLElement; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement; + querySelector(selectors: "form"): HTMLFormElement; + querySelector(selectors: "frame"): HTMLFrameElement; + querySelector(selectors: "frameset"): HTMLFrameSetElement; + querySelector(selectors: "g"): SVGGElement; + querySelector(selectors: "h1"): HTMLHeadingElement; + querySelector(selectors: "h2"): HTMLHeadingElement; + querySelector(selectors: "h3"): HTMLHeadingElement; + querySelector(selectors: "h4"): HTMLHeadingElement; + querySelector(selectors: "h5"): HTMLHeadingElement; + querySelector(selectors: "h6"): HTMLHeadingElement; + querySelector(selectors: "head"): HTMLHeadElement; + querySelector(selectors: "header"): HTMLElement; + querySelector(selectors: "hgroup"): HTMLElement; + querySelector(selectors: "hr"): HTMLHRElement; + querySelector(selectors: "html"): HTMLHtmlElement; + querySelector(selectors: "i"): HTMLElement; + querySelector(selectors: "iframe"): HTMLIFrameElement; + querySelector(selectors: "image"): SVGImageElement; + querySelector(selectors: "img"): HTMLImageElement; + querySelector(selectors: "input"): HTMLInputElement; + querySelector(selectors: "ins"): HTMLModElement; + querySelector(selectors: "isindex"): HTMLUnknownElement; + querySelector(selectors: "kbd"): HTMLElement; + querySelector(selectors: "keygen"): HTMLElement; + querySelector(selectors: "label"): HTMLLabelElement; + querySelector(selectors: "legend"): HTMLLegendElement; + querySelector(selectors: "li"): HTMLLIElement; + querySelector(selectors: "line"): SVGLineElement; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement; + querySelector(selectors: "link"): HTMLLinkElement; + querySelector(selectors: "listing"): HTMLPreElement; + querySelector(selectors: "map"): HTMLMapElement; + querySelector(selectors: "mark"): HTMLElement; + querySelector(selectors: "marker"): SVGMarkerElement; + querySelector(selectors: "marquee"): HTMLMarqueeElement; + querySelector(selectors: "mask"): SVGMaskElement; + querySelector(selectors: "menu"): HTMLMenuElement; + querySelector(selectors: "meta"): HTMLMetaElement; + querySelector(selectors: "metadata"): SVGMetadataElement; + querySelector(selectors: "meter"): HTMLMeterElement; + querySelector(selectors: "nav"): HTMLElement; + querySelector(selectors: "nextid"): HTMLUnknownElement; + querySelector(selectors: "nobr"): HTMLElement; + querySelector(selectors: "noframes"): HTMLElement; + querySelector(selectors: "noscript"): HTMLElement; + querySelector(selectors: "object"): HTMLObjectElement; + querySelector(selectors: "ol"): HTMLOListElement; + querySelector(selectors: "optgroup"): HTMLOptGroupElement; + querySelector(selectors: "option"): HTMLOptionElement; + querySelector(selectors: "p"): HTMLParagraphElement; + querySelector(selectors: "param"): HTMLParamElement; + querySelector(selectors: "path"): SVGPathElement; + querySelector(selectors: "pattern"): SVGPatternElement; + querySelector(selectors: "picture"): HTMLPictureElement; + querySelector(selectors: "plaintext"): HTMLElement; + querySelector(selectors: "polygon"): SVGPolygonElement; + querySelector(selectors: "polyline"): SVGPolylineElement; + querySelector(selectors: "pre"): HTMLPreElement; + querySelector(selectors: "progress"): HTMLProgressElement; + querySelector(selectors: "q"): HTMLQuoteElement; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement; + querySelector(selectors: "rect"): SVGRectElement; + querySelector(selectors: "rt"): HTMLElement; + querySelector(selectors: "ruby"): HTMLElement; + querySelector(selectors: "s"): HTMLElement; + querySelector(selectors: "samp"): HTMLElement; + querySelector(selectors: "script"): HTMLScriptElement; + querySelector(selectors: "section"): HTMLElement; + querySelector(selectors: "select"): HTMLSelectElement; + querySelector(selectors: "small"): HTMLElement; + querySelector(selectors: "source"): HTMLSourceElement; + querySelector(selectors: "span"): HTMLSpanElement; + querySelector(selectors: "stop"): SVGStopElement; + querySelector(selectors: "strike"): HTMLElement; + querySelector(selectors: "strong"): HTMLElement; + querySelector(selectors: "style"): HTMLStyleElement; + querySelector(selectors: "sub"): HTMLElement; + querySelector(selectors: "sup"): HTMLElement; + querySelector(selectors: "svg"): SVGSVGElement; + querySelector(selectors: "switch"): SVGSwitchElement; + querySelector(selectors: "symbol"): SVGSymbolElement; + querySelector(selectors: "table"): HTMLTableElement; + querySelector(selectors: "tbody"): HTMLTableSectionElement; + querySelector(selectors: "td"): HTMLTableDataCellElement; + querySelector(selectors: "template"): HTMLTemplateElement; + querySelector(selectors: "text"): SVGTextElement; + querySelector(selectors: "textpath"): SVGTextPathElement; + querySelector(selectors: "textarea"): HTMLTextAreaElement; + querySelector(selectors: "tfoot"): HTMLTableSectionElement; + querySelector(selectors: "th"): HTMLTableHeaderCellElement; + querySelector(selectors: "thead"): HTMLTableSectionElement; + querySelector(selectors: "title"): HTMLTitleElement; + querySelector(selectors: "tr"): HTMLTableRowElement; + querySelector(selectors: "track"): HTMLTrackElement; + querySelector(selectors: "tspan"): SVGTSpanElement; + querySelector(selectors: "tt"): HTMLElement; + querySelector(selectors: "u"): HTMLElement; + querySelector(selectors: "ul"): HTMLUListElement; + querySelector(selectors: "use"): SVGUseElement; + querySelector(selectors: "var"): HTMLElement; + querySelector(selectors: "video"): HTMLVideoElement; + querySelector(selectors: "view"): SVGViewElement; + querySelector(selectors: "wbr"): HTMLElement; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; + querySelector(selectors: "xmp"): HTMLPreElement; querySelector(selectors: string): Element; + querySelectorAll(selectors: "a"): NodeListOf; + querySelectorAll(selectors: "abbr"): NodeListOf; + querySelectorAll(selectors: "acronym"): NodeListOf; + querySelectorAll(selectors: "address"): NodeListOf; + querySelectorAll(selectors: "applet"): NodeListOf; + querySelectorAll(selectors: "area"): NodeListOf; + querySelectorAll(selectors: "article"): NodeListOf; + querySelectorAll(selectors: "aside"): NodeListOf; + querySelectorAll(selectors: "audio"): NodeListOf; + querySelectorAll(selectors: "b"): NodeListOf; + querySelectorAll(selectors: "base"): NodeListOf; + querySelectorAll(selectors: "basefont"): NodeListOf; + querySelectorAll(selectors: "bdo"): NodeListOf; + querySelectorAll(selectors: "big"): NodeListOf; + querySelectorAll(selectors: "blockquote"): NodeListOf; + querySelectorAll(selectors: "body"): NodeListOf; + querySelectorAll(selectors: "br"): NodeListOf; + querySelectorAll(selectors: "button"): NodeListOf; + querySelectorAll(selectors: "canvas"): NodeListOf; + querySelectorAll(selectors: "caption"): NodeListOf; + querySelectorAll(selectors: "center"): NodeListOf; + querySelectorAll(selectors: "circle"): NodeListOf; + querySelectorAll(selectors: "cite"): NodeListOf; + querySelectorAll(selectors: "clippath"): NodeListOf; + querySelectorAll(selectors: "code"): NodeListOf; + querySelectorAll(selectors: "col"): NodeListOf; + querySelectorAll(selectors: "colgroup"): NodeListOf; + querySelectorAll(selectors: "datalist"): NodeListOf; + querySelectorAll(selectors: "dd"): NodeListOf; + querySelectorAll(selectors: "defs"): NodeListOf; + querySelectorAll(selectors: "del"): NodeListOf; + querySelectorAll(selectors: "desc"): NodeListOf; + querySelectorAll(selectors: "dfn"): NodeListOf; + querySelectorAll(selectors: "dir"): NodeListOf; + querySelectorAll(selectors: "div"): NodeListOf; + querySelectorAll(selectors: "dl"): NodeListOf; + querySelectorAll(selectors: "dt"): NodeListOf; + querySelectorAll(selectors: "ellipse"): NodeListOf; + querySelectorAll(selectors: "em"): NodeListOf; + querySelectorAll(selectors: "embed"): NodeListOf; + querySelectorAll(selectors: "feblend"): NodeListOf; + querySelectorAll(selectors: "fecolormatrix"): NodeListOf; + querySelectorAll(selectors: "fecomponenttransfer"): NodeListOf; + querySelectorAll(selectors: "fecomposite"): NodeListOf; + querySelectorAll(selectors: "feconvolvematrix"): NodeListOf; + querySelectorAll(selectors: "fediffuselighting"): NodeListOf; + querySelectorAll(selectors: "fedisplacementmap"): NodeListOf; + querySelectorAll(selectors: "fedistantlight"): NodeListOf; + querySelectorAll(selectors: "feflood"): NodeListOf; + querySelectorAll(selectors: "fefunca"): NodeListOf; + querySelectorAll(selectors: "fefuncb"): NodeListOf; + querySelectorAll(selectors: "fefuncg"): NodeListOf; + querySelectorAll(selectors: "fefuncr"): NodeListOf; + querySelectorAll(selectors: "fegaussianblur"): NodeListOf; + querySelectorAll(selectors: "feimage"): NodeListOf; + querySelectorAll(selectors: "femerge"): NodeListOf; + querySelectorAll(selectors: "femergenode"): NodeListOf; + querySelectorAll(selectors: "femorphology"): NodeListOf; + querySelectorAll(selectors: "feoffset"): NodeListOf; + querySelectorAll(selectors: "fepointlight"): NodeListOf; + querySelectorAll(selectors: "fespecularlighting"): NodeListOf; + querySelectorAll(selectors: "fespotlight"): NodeListOf; + querySelectorAll(selectors: "fetile"): NodeListOf; + querySelectorAll(selectors: "feturbulence"): NodeListOf; + querySelectorAll(selectors: "fieldset"): NodeListOf; + querySelectorAll(selectors: "figcaption"): NodeListOf; + querySelectorAll(selectors: "figure"): NodeListOf; + querySelectorAll(selectors: "filter"): NodeListOf; + querySelectorAll(selectors: "font"): NodeListOf; + querySelectorAll(selectors: "footer"): NodeListOf; + querySelectorAll(selectors: "foreignobject"): NodeListOf; + querySelectorAll(selectors: "form"): NodeListOf; + querySelectorAll(selectors: "frame"): NodeListOf; + querySelectorAll(selectors: "frameset"): NodeListOf; + querySelectorAll(selectors: "g"): NodeListOf; + querySelectorAll(selectors: "h1"): NodeListOf; + querySelectorAll(selectors: "h2"): NodeListOf; + querySelectorAll(selectors: "h3"): NodeListOf; + querySelectorAll(selectors: "h4"): NodeListOf; + querySelectorAll(selectors: "h5"): NodeListOf; + querySelectorAll(selectors: "h6"): NodeListOf; + querySelectorAll(selectors: "head"): NodeListOf; + querySelectorAll(selectors: "header"): NodeListOf; + querySelectorAll(selectors: "hgroup"): NodeListOf; + querySelectorAll(selectors: "hr"): NodeListOf; + querySelectorAll(selectors: "html"): NodeListOf; + querySelectorAll(selectors: "i"): NodeListOf; + querySelectorAll(selectors: "iframe"): NodeListOf; + querySelectorAll(selectors: "image"): NodeListOf; + querySelectorAll(selectors: "img"): NodeListOf; + querySelectorAll(selectors: "input"): NodeListOf; + querySelectorAll(selectors: "ins"): NodeListOf; + querySelectorAll(selectors: "isindex"): NodeListOf; + querySelectorAll(selectors: "kbd"): NodeListOf; + querySelectorAll(selectors: "keygen"): NodeListOf; + querySelectorAll(selectors: "label"): NodeListOf; + querySelectorAll(selectors: "legend"): NodeListOf; + querySelectorAll(selectors: "li"): NodeListOf; + querySelectorAll(selectors: "line"): NodeListOf; + querySelectorAll(selectors: "lineargradient"): NodeListOf; + querySelectorAll(selectors: "link"): NodeListOf; + querySelectorAll(selectors: "listing"): NodeListOf; + querySelectorAll(selectors: "map"): NodeListOf; + querySelectorAll(selectors: "mark"): NodeListOf; + querySelectorAll(selectors: "marker"): NodeListOf; + querySelectorAll(selectors: "marquee"): NodeListOf; + querySelectorAll(selectors: "mask"): NodeListOf; + querySelectorAll(selectors: "menu"): NodeListOf; + querySelectorAll(selectors: "meta"): NodeListOf; + querySelectorAll(selectors: "metadata"): NodeListOf; + querySelectorAll(selectors: "meter"): NodeListOf; + querySelectorAll(selectors: "nav"): NodeListOf; + querySelectorAll(selectors: "nextid"): NodeListOf; + querySelectorAll(selectors: "nobr"): NodeListOf; + querySelectorAll(selectors: "noframes"): NodeListOf; + querySelectorAll(selectors: "noscript"): NodeListOf; + querySelectorAll(selectors: "object"): NodeListOf; + querySelectorAll(selectors: "ol"): NodeListOf; + querySelectorAll(selectors: "optgroup"): NodeListOf; + querySelectorAll(selectors: "option"): NodeListOf; + querySelectorAll(selectors: "p"): NodeListOf; + querySelectorAll(selectors: "param"): NodeListOf; + querySelectorAll(selectors: "path"): NodeListOf; + querySelectorAll(selectors: "pattern"): NodeListOf; + querySelectorAll(selectors: "picture"): NodeListOf; + querySelectorAll(selectors: "plaintext"): NodeListOf; + querySelectorAll(selectors: "polygon"): NodeListOf; + querySelectorAll(selectors: "polyline"): NodeListOf; + querySelectorAll(selectors: "pre"): NodeListOf; + querySelectorAll(selectors: "progress"): NodeListOf; + querySelectorAll(selectors: "q"): NodeListOf; + querySelectorAll(selectors: "radialgradient"): NodeListOf; + querySelectorAll(selectors: "rect"): NodeListOf; + querySelectorAll(selectors: "rt"): NodeListOf; + querySelectorAll(selectors: "ruby"): NodeListOf; + querySelectorAll(selectors: "s"): NodeListOf; + querySelectorAll(selectors: "samp"): NodeListOf; + querySelectorAll(selectors: "script"): NodeListOf; + querySelectorAll(selectors: "section"): NodeListOf; + querySelectorAll(selectors: "select"): NodeListOf; + querySelectorAll(selectors: "small"): NodeListOf; + querySelectorAll(selectors: "source"): NodeListOf; + querySelectorAll(selectors: "span"): NodeListOf; + querySelectorAll(selectors: "stop"): NodeListOf; + querySelectorAll(selectors: "strike"): NodeListOf; + querySelectorAll(selectors: "strong"): NodeListOf; + querySelectorAll(selectors: "style"): NodeListOf; + querySelectorAll(selectors: "sub"): NodeListOf; + querySelectorAll(selectors: "sup"): NodeListOf; + querySelectorAll(selectors: "svg"): NodeListOf; + querySelectorAll(selectors: "switch"): NodeListOf; + querySelectorAll(selectors: "symbol"): NodeListOf; + querySelectorAll(selectors: "table"): NodeListOf; + querySelectorAll(selectors: "tbody"): NodeListOf; + querySelectorAll(selectors: "td"): NodeListOf; + querySelectorAll(selectors: "template"): NodeListOf; + querySelectorAll(selectors: "text"): NodeListOf; + querySelectorAll(selectors: "textpath"): NodeListOf; + querySelectorAll(selectors: "textarea"): NodeListOf; + querySelectorAll(selectors: "tfoot"): NodeListOf; + querySelectorAll(selectors: "th"): NodeListOf; + querySelectorAll(selectors: "thead"): NodeListOf; + querySelectorAll(selectors: "title"): NodeListOf; + querySelectorAll(selectors: "tr"): NodeListOf; + querySelectorAll(selectors: "track"): NodeListOf; + querySelectorAll(selectors: "tspan"): NodeListOf; + querySelectorAll(selectors: "tt"): NodeListOf; + querySelectorAll(selectors: "u"): NodeListOf; + querySelectorAll(selectors: "ul"): NodeListOf; + querySelectorAll(selectors: "use"): NodeListOf; + querySelectorAll(selectors: "var"): NodeListOf; + querySelectorAll(selectors: "video"): NodeListOf; + querySelectorAll(selectors: "view"): NodeListOf; + querySelectorAll(selectors: "wbr"): NodeListOf; + querySelectorAll(selectors: "x-ms-webview"): NodeListOf; + querySelectorAll(selectors: "xmp"): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -17711,18 +18085,21 @@ interface WindowSessionStorage { interface WindowTimers extends Object, WindowTimersExtension { clearInterval(handle: number): void; clearTimeout(handle: number): void; + setInterval(handler: (...args: any[]) => void, timeout: number): number; setInterval(handler: any, timeout?: any, ...args: any[]): number; + setTimeout(handler: (...args: any[]) => void, timeout: number): number; setTimeout(handler: any, timeout?: any, ...args: any[]): number; } interface WindowTimersExtension { clearImmediate(handle: number): void; - setImmediate(expression: any, ...args: any[]): number; + setImmediate(handler: (...args: any[]) => void): number; + setImmediate(handler: any, ...args: any[]): number; } interface XMLHttpRequestEventTarget { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -17746,6 +18123,13 @@ interface StorageEventInit extends EventInit { storageArea?: Storage; } +interface Canvas2DContextAttributes { + alpha?: boolean; + willReadFrequently?: boolean; + storage?: boolean; + [attribute: string]: boolean | string | undefined; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -17795,6 +18179,177 @@ interface ClipboardEventInit extends EventInit { interface IDBArrayKey extends Array { } +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: AlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: AlgorithmIdentifier; +} + +interface RsaHashedImportParams { + hash: AlgorithmIdentifier; +} + +interface RsaPssParams { + saltLength: number; +} + +interface RsaOaepParams extends Algorithm { + label?: BufferSource; +} + +interface EcdsaParams extends Algorithm { + hash: AlgorithmIdentifier; +} + +interface EcKeyGenParams extends Algorithm { + typedCurve: string; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + typedCurve: string; +} + +interface EcKeyImportParams { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + iv: BufferSource; + additionalData?: BufferSource; + tagLength?: number; +} + +interface AesCfbParams extends Algorithm { + iv: BufferSource; +} + +interface HmacImportParams extends Algorithm { + hash?: AlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: AlgorithmIdentifier; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: AlgorithmIdentifier; + length?: number; +} + +interface DhKeyGenParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhImportKeyParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface ConcatParams extends Algorithm { + hash?: AlgorithmIdentifier; + algorithmId: Uint8Array; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + publicInfo?: Uint8Array; + privateInfo?: Uint8Array; +} + +interface HkdfCtrParams extends Algorithm { + hash: AlgorithmIdentifier; + label: BufferSource; + context: BufferSource; +} + +interface Pbkdf2Params extends Algorithm { + salt: BufferSource; + iterations: number; + hash: AlgorithmIdentifier; +} + +interface RsaOtherPrimesInfo { + r: string; + d: string; + t: string; +} + +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + kid?: string; + x5u?: string; + x5c?: string; + x5t?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -17868,7 +18423,7 @@ declare var msCredentials: MSCredentials; declare var name: string; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; -declare var onabort: (ev: Event) => any; +declare var onabort: (ev: UIEvent) => any; declare var onafterprint: (ev: Event) => any; declare var onbeforeprint: (ev: Event) => any; declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -18018,10 +18573,13 @@ declare function dispatchEvent(evt: Event): boolean; declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; +declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number; declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; declare function clearImmediate(handle: number): void; -declare function setImmediate(expression: any, ...args: any[]): number; +declare function setImmediate(handler: (...args: any[]) => void): number; +declare function setImmediate(handler: any, ...args: any[]): number; declare var sessionStorage: Storage; declare var localStorage: Storage; declare var console: Console; @@ -18165,6 +18723,8 @@ type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; type payloadtype = number; type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; +type MouseWheelEvent = WheelEvent; ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 673bd34ee3c..117168cb9d1 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -20,7 +20,7 @@ and limitations under the License. ///////////////////////////// interface Algorithm { - name?: string; + name: string; } interface AriaRequestEventInit extends EventInit { @@ -867,6 +867,7 @@ interface UIEventInit extends EventInit { } interface WebGLContextAttributes { + failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; depth?: boolean; stencil?: boolean; @@ -935,7 +936,7 @@ interface ApplicationCache extends EventTarget { oncached: (ev: Event) => any; onchecking: (ev: Event) => any; ondownloading: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onnoupdate: (ev: Event) => any; onobsolete: (ev: Event) => any; onprogress: (ev: ProgressEvent) => any; @@ -2305,7 +2306,7 @@ declare var DeviceRotationRate: { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent { /** - * Sets or gets the URL for the current document. + * Sets or gets the URL for the current document. */ readonly URL: string; /** @@ -2333,7 +2334,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ bgColor: string; /** @@ -2361,19 +2362,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. + * Sets or retrieves a value that indicates the reading order of the object. */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. + * Gets an object representing the document type declaration associated with the current document. */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. + * Gets a reference to the root node of the document. */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. + * Sets or gets the security domain of the document. */ domain: string; /** @@ -2397,7 +2398,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. + * Gets the implementation object of the current document. */ readonly implementation: DOMImplementation; /** @@ -2405,11 +2406,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. + * Gets the date that the page was last modified, if the page supplies one. */ readonly lastModified: string; /** - * Sets or gets the color of the document links. + * Sets or gets the color of the document links. */ linkColor: string; /** @@ -2417,7 +2418,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ links: HTMLCollectionOf; /** - * Contains information about the current URL. + * Contains information about the current URL. */ readonly location: Location; msCSSOMElementFloatMetrics: boolean; @@ -2426,7 +2427,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when the user aborts the download. * @param ev The event. */ - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; /** * Fires when the object is set as the active element. * @param ev The event. @@ -2442,19 +2443,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ onbeforedeactivate: (ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. + /** + * Fires when the object loses the input focus. * @param ev The focus event. */ onblur: (ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. + * Occurs when playback is possible, but would require further buffering. * @param ev The event. */ oncanplay: (ev: Event) => any; oncanplaythrough: (ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. + * Fires when the contents of the object or selection have changed. * @param ev The event. */ onchange: (ev: Event) => any; @@ -2464,7 +2465,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onclick: (ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * Fires when the user clicks the right mouse button in the client area, opening the context menu. * @param ev The mouse event. */ oncontextmenu: (ev: PointerEvent) => any; @@ -2488,12 +2489,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ ondragend: (ev: DragEvent) => any; - /** + /** * Fires on the target element when the user drags the object to a valid drop target. * @param ev The drag event. */ ondragenter: (ev: DragEvent) => any; - /** + /** * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. * @param ev The drag event. */ @@ -2504,23 +2505,23 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ ondragover: (ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. + * Fires on the source object when the user starts to drag a text selection or selected object. * @param ev The event. */ ondragstart: (ev: DragEvent) => any; ondrop: (ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. + * Occurs when the duration attribute is updated. * @param ev The event. */ ondurationchange: (ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. + * Occurs when the media element is reset to its initial state. * @param ev The event. */ onemptied: (ev: Event) => any; /** - * Occurs when the end of playback is reached. + * Occurs when the end of playback is reached. * @param ev The event */ onended: (ev: MediaStreamErrorEvent) => any; @@ -2528,9 +2529,9 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** - * Fires when the object receives focus. + * Fires when the object receives focus. * @param ev The event. */ onfocus: (ev: FocusEvent) => any; @@ -2554,12 +2555,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onkeyup: (ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. + * Fires immediately after the browser loads the object. * @param ev The event. */ onload: (ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. + * Occurs when media data is loaded at the current playback position. * @param ev The event. */ onloadeddata: (ev: Event) => any; @@ -2569,22 +2570,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onloadedmetadata: (ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. + * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ onloadstart: (ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. + * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ onmousedown: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. + * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ onmousemove: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. + * Fires when the user moves the mouse pointer outside the boundaries of the object. * @param ev The mouse event. */ onmouseout: (ev: MouseEvent) => any; @@ -2594,12 +2595,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onmouseover: (ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. + * Fires when the user releases a mouse button while the mouse is over the object. * @param ev The mouse event. */ onmouseup: (ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. + * Fires when the wheel button is rotated. * @param ev The mouse event */ onmousewheel: (ev: WheelEvent) => any; @@ -2621,7 +2622,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (ev: MSPointerEvent) => any; onmspointerup: (ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. * @param ev The event. */ onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; @@ -2636,24 +2637,24 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onpause: (ev: Event) => any; /** - * Occurs when the play method is requested. + * Occurs when the play method is requested. * @param ev The event. */ onplay: (ev: Event) => any; /** - * Occurs when the audio or video has started playing. + * Occurs when the audio or video has started playing. * @param ev The event. */ onplaying: (ev: Event) => any; onpointerlockchange: (ev: Event) => any; onpointerlockerror: (ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. + * Occurs to indicate progress while downloading media data. * @param ev The event. */ onprogress: (ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. + * Occurs when the playback rate is increased or decreased. * @param ev The event. */ onratechange: (ev: Event) => any; @@ -2663,22 +2664,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onreadystatechange: (ev: ProgressEvent) => any; /** - * Fires when the user resets a form. + * Fires when the user resets a form. * @param ev The event. */ onreset: (ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. + * Fires when the user repositions the scroll box in the scroll bar on the object. * @param ev The event. */ onscroll: (ev: UIEvent) => any; /** - * Occurs when the seek operation ends. + * Occurs when the seek operation ends. * @param ev The event. */ onseeked: (ev: Event) => any; /** - * Occurs when the current playback position is moved. + * Occurs when the current playback position is moved. * @param ev The event. */ onseeking: (ev: Event) => any; @@ -2694,7 +2695,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onselectionchange: (ev: Event) => any; onselectstart: (ev: Event) => any; /** - * Occurs when the download has stopped. + * Occurs when the download has stopped. * @param ev The event. */ onstalled: (ev: Event) => any; @@ -2705,7 +2706,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onstop: (ev: Event) => any; onsubmit: (ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. + * Occurs if the load operation has been intentionally halted. * @param ev The event. */ onsuspend: (ev: Event) => any; @@ -2724,7 +2725,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onvolumechange: (ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. + * Occurs when playback stops because the next frame of a video resource is not available. * @param ev The event. */ onwaiting: (ev: Event) => any; @@ -2758,7 +2759,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ title: string; readonly visibilityState: string; - /** + /** * Sets or gets the color of the links that the user has visited. */ vlinkColor: string; @@ -2948,7 +2949,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. * @param root The root element or node to start traversing on. * @param whatToShow The type of nodes or elements to appear in the node list * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. @@ -2957,11 +2958,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. */ createRange(): Range; /** - * Creates a text string from the specified value. + * Creates a text string from the specified value. * @param data String that specifies the nodeValue property of the text node. */ createTextNode(data: string): Text; @@ -2976,7 +2977,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. + * Returns the element for the specified x coordinate and the specified y coordinate. * @param x The x-offset * @param y The y-offset */ @@ -3004,7 +3005,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Returns a reference to the first object with the specified value of the ID or NAME attribute. * @param elementId String that specifies the ID value. Case-insensitive. */ - getElementById(elementId: string): HTMLElement; + getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** * Gets a collection of objects based on the value of the NAME or ID attribute. @@ -3214,7 +3215,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param replace Specifies whether the existing entry for the document is replaced in the history list. */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** + /** * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. * @param commandId Specifies a command identifier. */ @@ -3236,7 +3237,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven queryCommandSupported(commandId: string): boolean; /** * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. */ queryCommandText(commandId: string): string; /** @@ -3252,12 +3253,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. + * Writes one or more HTML expressions to a document in the specified window. * @param content Specifies the text and HTML tags to write. */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; @@ -3479,7 +3480,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec readonly scrollWidth: number; readonly tagName: string; innerHTML: string; - getAttribute(name?: string): string | null; + getAttribute(name: string): string | null; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; @@ -3689,6 +3690,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: string): Element | null; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -3985,12 +3987,12 @@ interface HTMLAnchorElement extends HTMLElement { */ target: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; type: string; urn: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -4092,7 +4094,7 @@ interface HTMLAreaElement extends HTMLElement { */ host: string; /** - * Sets or retrieves the host name part of the location or URL. + * Sets or retrieves the host name part of the location or URL. */ hostname: string; /** @@ -4128,7 +4130,7 @@ interface HTMLAreaElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -4219,7 +4221,7 @@ interface HTMLBodyElement extends HTMLElement { onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; onhashchange: (ev: HashChangeEvent) => any; onload: (ev: Event) => any; @@ -4394,7 +4396,7 @@ interface HTMLButtonElement extends HTMLElement { * Overrides the target attribute on a form element. */ formTarget: string; - /** + /** * Sets or retrieves the name of the object. */ name: string; @@ -4411,7 +4413,7 @@ interface HTMLButtonElement extends HTMLElement { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; - /** + /** * Sets or retrieves the default or selected value of the control. */ value: string; @@ -4448,9 +4450,9 @@ interface HTMLCanvasElement extends HTMLElement { * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); */ - getContext(contextId: "2d"): CanvasRenderingContext2D; - getContext(contextId: "experimental-webgl"): WebGLRenderingContext; - getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext; + getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; + getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; + getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ @@ -4460,7 +4462,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; - toBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, ... arguments: any[]): void; } declare var HTMLCanvasElement: { @@ -4518,7 +4520,7 @@ declare var HTMLDirectoryElement: { interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; /** @@ -4558,7 +4560,7 @@ interface HTMLElement extends Element { readonly offsetParent: Element; readonly offsetTop: number; readonly offsetWidth: number; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onactivate: (ev: UIEvent) => any; onbeforeactivate: (ev: UIEvent) => any; onbeforecopy: (ev: ClipboardEvent) => any; @@ -4586,7 +4588,7 @@ interface HTMLElement extends Element { ondurationchange: (ev: Event) => any; onemptied: (ev: Event) => any; onended: (ev: MediaStreamErrorEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; oninput: (ev: Event) => any; oninvalid: (ev: Event) => any; @@ -5136,7 +5138,7 @@ interface HTMLFrameSetElement extends HTMLElement { * Fires when the object loses the input focus. */ onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** * Fires when the object receives focus. */ @@ -5659,9 +5661,9 @@ interface HTMLInputElement extends HTMLElement { /** * Returns a FileList object on a file type input object. */ - readonly files: FileList; + readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -6381,7 +6383,7 @@ interface HTMLMetaElement extends HTMLElement { */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; } @@ -6630,7 +6632,7 @@ declare var HTMLOptionElement: { create(): HTMLOptionElement; } -interface HTMLOptionsCollection extends HTMLCollection { +interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; @@ -6644,7 +6646,7 @@ declare var HTMLOptionsCollection: { interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; clear: string; @@ -6746,10 +6748,10 @@ interface HTMLScriptElement extends HTMLElement { */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. + * Sets or retrieves the event for which the script is written. */ event: string; - /** + /** * Sets or retrieves the object that is bound to the event script. */ htmlFor: string; @@ -6758,7 +6760,7 @@ interface HTMLScriptElement extends HTMLElement { */ src: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; /** @@ -6779,7 +6781,7 @@ interface HTMLSelectElement extends HTMLElement { autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -6794,7 +6796,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLCollectionOf; + readonly options: HTMLOptionsCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -6805,7 +6807,7 @@ interface HTMLSelectElement extends HTMLElement { selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. + * Sets or retrieves the number of rows in the list box. */ size: number; /** @@ -6831,7 +6833,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. */ add(element: HTMLElement, before?: HTMLElement | number): void; /** @@ -7026,7 +7028,7 @@ interface HTMLTableElement extends HTMLElement { */ border: string; /** - * Sets or retrieves the border color of the object. + * Sets or retrieves the border color of the object. */ borderColor: any; /** @@ -7321,7 +7323,7 @@ declare var HTMLTextAreaElement: { interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; } @@ -7590,7 +7592,7 @@ interface IDBDatabase extends EventTarget { readonly name: string; readonly objectStoreNames: DOMStringList; onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; version: number; onversionchange: (ev: IDBVersionChangeEvent) => any; close(): void; @@ -7693,7 +7695,7 @@ declare var IDBOpenDBRequest: { interface IDBRequest extends EventTarget { readonly error: DOMError; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onsuccess: (ev: Event) => any; readonly readyState: string; readonly result: any; @@ -7715,7 +7717,7 @@ interface IDBTransaction extends EventTarget { readonly mode: string; onabort: (ev: Event) => any; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -7858,7 +7860,7 @@ declare var MSApp: MSApp; interface MSAppAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; start(): void; @@ -8218,7 +8220,7 @@ declare var MSStreamReader: { interface MSWebViewAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; readonly target: MSHTMLWebViewElement; @@ -8754,7 +8756,7 @@ interface Node extends EventTarget { contains(child: Node): boolean; hasAttributes(): boolean; hasChildNodes(): boolean; - insertBefore(newChild: Node, refChild: Node): Node; + insertBefore(newChild: Node, refChild: Node | null): Node; isDefaultNamespace(namespaceURI: string | null): boolean; isEqualNode(arg: Node): boolean; isSameNode(other: Node): boolean; @@ -8763,7 +8765,6 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; - contains(node: Node): boolean; readonly ATTRIBUTE_NODE: number; readonly CDATA_SECTION_NODE: number; readonly COMMENT_NODE: number; @@ -9299,7 +9300,7 @@ declare var RTCDTMFToneChangeEvent: { interface RTCDtlsTransport extends RTCStatsProvider { ondtlsstatechange: ((ev: RTCDtlsTransportStateChangedEvent) => any) | null; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly state: string; readonly transport: RTCIceTransport; getLocalParameters(): RTCDtlsParameters; @@ -9354,7 +9355,7 @@ declare var RTCIceCandidatePairChangedEvent: { interface RTCIceGatherer extends RTCStatsProvider { readonly component: string; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onlocalcandidate: ((ev: RTCIceGathererEvent) => any) | null; createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidate[]; @@ -9413,7 +9414,7 @@ declare var RTCIceTransportStateChangedEvent: { } interface RTCRtpReceiver extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -9433,7 +9434,7 @@ declare var RTCRtpReceiver: { } interface RTCRtpSender extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onssrcconflict: ((ev: RTCSsrcConflictEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack; @@ -9454,7 +9455,7 @@ declare var RTCRtpSender: { } interface RTCSrtpSdesTransport extends EventTarget { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly transport: RTCIceTransport; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11494,18 +11495,24 @@ declare var StyleSheetPageList: { } interface SubtleCrypto { - decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: string | Algorithm, data: ArrayBufferView): PromiseLike; - encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; } declare var SubtleCrypto: { @@ -11573,7 +11580,7 @@ interface TextTrack extends EventTarget { readonly language: string; mode: any; oncuechange: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; readonly readyState: number; addCue(cue: TextTrackCue): void; @@ -12062,18 +12069,12 @@ interface WebGLRenderingContext { stencilMaskSeparate(face: number, mask: number): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; - texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels?: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; texParameterf(target: number, pname: number, param: number): void; texParameteri(target: number, pname: number, param: number): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels?: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; uniform1f(location: WebGLUniformLocation | null, x: number): void; uniform1fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; uniform1i(location: WebGLUniformLocation | null, x: number): void; @@ -12796,7 +12797,7 @@ interface WebSocket extends EventTarget { readonly bufferedAmount: number; readonly extensions: string; onclose: (ev: CloseEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onmessage: (ev: MessageEvent) => any; onopen: (ev: Event) => any; readonly protocol: string; @@ -12871,7 +12872,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window name: string; readonly navigator: Navigator; offscreenBuffering: string | boolean; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onafterprint: (ev: Event) => any; onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -12987,6 +12988,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly top: Window; readonly window: Window; URL: typeof URL; + Blob: typeof Blob; alert(message?: any): void; blur(): void; cancelAnimationFrame(handle: number): void; @@ -13143,7 +13145,6 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - msCaching: string; onreadystatechange: (ev: ProgressEvent) => any; readonly readyState: number; readonly response: any; @@ -13155,6 +13156,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { timeout: number; readonly upload: XMLHttpRequestUpload; withCredentials: boolean; + msCaching?: string; abort(): void; getAllResponseHeaders(): string; getResponseHeader(header: string): string | null; @@ -13293,7 +13295,7 @@ declare var XSLTProcessor: { } interface AbstractWorker { - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13452,7 +13454,7 @@ interface LinkStyle { interface MSBaseReader { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -13517,7 +13519,359 @@ interface NavigatorUserMedia { } interface NodeSelector { + querySelector(selectors: "a"): HTMLAnchorElement; + querySelector(selectors: "abbr"): HTMLElement; + querySelector(selectors: "acronym"): HTMLElement; + querySelector(selectors: "address"): HTMLElement; + querySelector(selectors: "applet"): HTMLAppletElement; + querySelector(selectors: "area"): HTMLAreaElement; + querySelector(selectors: "article"): HTMLElement; + querySelector(selectors: "aside"): HTMLElement; + querySelector(selectors: "audio"): HTMLAudioElement; + querySelector(selectors: "b"): HTMLElement; + querySelector(selectors: "base"): HTMLBaseElement; + querySelector(selectors: "basefont"): HTMLBaseFontElement; + querySelector(selectors: "bdo"): HTMLElement; + querySelector(selectors: "big"): HTMLElement; + querySelector(selectors: "blockquote"): HTMLQuoteElement; + querySelector(selectors: "body"): HTMLBodyElement; + querySelector(selectors: "br"): HTMLBRElement; + querySelector(selectors: "button"): HTMLButtonElement; + querySelector(selectors: "canvas"): HTMLCanvasElement; + querySelector(selectors: "caption"): HTMLTableCaptionElement; + querySelector(selectors: "center"): HTMLElement; + querySelector(selectors: "circle"): SVGCircleElement; + querySelector(selectors: "cite"): HTMLElement; + querySelector(selectors: "clippath"): SVGClipPathElement; + querySelector(selectors: "code"): HTMLElement; + querySelector(selectors: "col"): HTMLTableColElement; + querySelector(selectors: "colgroup"): HTMLTableColElement; + querySelector(selectors: "datalist"): HTMLDataListElement; + querySelector(selectors: "dd"): HTMLElement; + querySelector(selectors: "defs"): SVGDefsElement; + querySelector(selectors: "del"): HTMLModElement; + querySelector(selectors: "desc"): SVGDescElement; + querySelector(selectors: "dfn"): HTMLElement; + querySelector(selectors: "dir"): HTMLDirectoryElement; + querySelector(selectors: "div"): HTMLDivElement; + querySelector(selectors: "dl"): HTMLDListElement; + querySelector(selectors: "dt"): HTMLElement; + querySelector(selectors: "ellipse"): SVGEllipseElement; + querySelector(selectors: "em"): HTMLElement; + querySelector(selectors: "embed"): HTMLEmbedElement; + querySelector(selectors: "feblend"): SVGFEBlendElement; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; + querySelector(selectors: "fecomposite"): SVGFECompositeElement; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; + querySelector(selectors: "feflood"): SVGFEFloodElement; + querySelector(selectors: "fefunca"): SVGFEFuncAElement; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; + querySelector(selectors: "feimage"): SVGFEImageElement; + querySelector(selectors: "femerge"): SVGFEMergeElement; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement; + querySelector(selectors: "feoffset"): SVGFEOffsetElement; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement; + querySelector(selectors: "fetile"): SVGFETileElement; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; + querySelector(selectors: "fieldset"): HTMLFieldSetElement; + querySelector(selectors: "figcaption"): HTMLElement; + querySelector(selectors: "figure"): HTMLElement; + querySelector(selectors: "filter"): SVGFilterElement; + querySelector(selectors: "font"): HTMLFontElement; + querySelector(selectors: "footer"): HTMLElement; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement; + querySelector(selectors: "form"): HTMLFormElement; + querySelector(selectors: "frame"): HTMLFrameElement; + querySelector(selectors: "frameset"): HTMLFrameSetElement; + querySelector(selectors: "g"): SVGGElement; + querySelector(selectors: "h1"): HTMLHeadingElement; + querySelector(selectors: "h2"): HTMLHeadingElement; + querySelector(selectors: "h3"): HTMLHeadingElement; + querySelector(selectors: "h4"): HTMLHeadingElement; + querySelector(selectors: "h5"): HTMLHeadingElement; + querySelector(selectors: "h6"): HTMLHeadingElement; + querySelector(selectors: "head"): HTMLHeadElement; + querySelector(selectors: "header"): HTMLElement; + querySelector(selectors: "hgroup"): HTMLElement; + querySelector(selectors: "hr"): HTMLHRElement; + querySelector(selectors: "html"): HTMLHtmlElement; + querySelector(selectors: "i"): HTMLElement; + querySelector(selectors: "iframe"): HTMLIFrameElement; + querySelector(selectors: "image"): SVGImageElement; + querySelector(selectors: "img"): HTMLImageElement; + querySelector(selectors: "input"): HTMLInputElement; + querySelector(selectors: "ins"): HTMLModElement; + querySelector(selectors: "isindex"): HTMLUnknownElement; + querySelector(selectors: "kbd"): HTMLElement; + querySelector(selectors: "keygen"): HTMLElement; + querySelector(selectors: "label"): HTMLLabelElement; + querySelector(selectors: "legend"): HTMLLegendElement; + querySelector(selectors: "li"): HTMLLIElement; + querySelector(selectors: "line"): SVGLineElement; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement; + querySelector(selectors: "link"): HTMLLinkElement; + querySelector(selectors: "listing"): HTMLPreElement; + querySelector(selectors: "map"): HTMLMapElement; + querySelector(selectors: "mark"): HTMLElement; + querySelector(selectors: "marker"): SVGMarkerElement; + querySelector(selectors: "marquee"): HTMLMarqueeElement; + querySelector(selectors: "mask"): SVGMaskElement; + querySelector(selectors: "menu"): HTMLMenuElement; + querySelector(selectors: "meta"): HTMLMetaElement; + querySelector(selectors: "metadata"): SVGMetadataElement; + querySelector(selectors: "meter"): HTMLMeterElement; + querySelector(selectors: "nav"): HTMLElement; + querySelector(selectors: "nextid"): HTMLUnknownElement; + querySelector(selectors: "nobr"): HTMLElement; + querySelector(selectors: "noframes"): HTMLElement; + querySelector(selectors: "noscript"): HTMLElement; + querySelector(selectors: "object"): HTMLObjectElement; + querySelector(selectors: "ol"): HTMLOListElement; + querySelector(selectors: "optgroup"): HTMLOptGroupElement; + querySelector(selectors: "option"): HTMLOptionElement; + querySelector(selectors: "p"): HTMLParagraphElement; + querySelector(selectors: "param"): HTMLParamElement; + querySelector(selectors: "path"): SVGPathElement; + querySelector(selectors: "pattern"): SVGPatternElement; + querySelector(selectors: "picture"): HTMLPictureElement; + querySelector(selectors: "plaintext"): HTMLElement; + querySelector(selectors: "polygon"): SVGPolygonElement; + querySelector(selectors: "polyline"): SVGPolylineElement; + querySelector(selectors: "pre"): HTMLPreElement; + querySelector(selectors: "progress"): HTMLProgressElement; + querySelector(selectors: "q"): HTMLQuoteElement; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement; + querySelector(selectors: "rect"): SVGRectElement; + querySelector(selectors: "rt"): HTMLElement; + querySelector(selectors: "ruby"): HTMLElement; + querySelector(selectors: "s"): HTMLElement; + querySelector(selectors: "samp"): HTMLElement; + querySelector(selectors: "script"): HTMLScriptElement; + querySelector(selectors: "section"): HTMLElement; + querySelector(selectors: "select"): HTMLSelectElement; + querySelector(selectors: "small"): HTMLElement; + querySelector(selectors: "source"): HTMLSourceElement; + querySelector(selectors: "span"): HTMLSpanElement; + querySelector(selectors: "stop"): SVGStopElement; + querySelector(selectors: "strike"): HTMLElement; + querySelector(selectors: "strong"): HTMLElement; + querySelector(selectors: "style"): HTMLStyleElement; + querySelector(selectors: "sub"): HTMLElement; + querySelector(selectors: "sup"): HTMLElement; + querySelector(selectors: "svg"): SVGSVGElement; + querySelector(selectors: "switch"): SVGSwitchElement; + querySelector(selectors: "symbol"): SVGSymbolElement; + querySelector(selectors: "table"): HTMLTableElement; + querySelector(selectors: "tbody"): HTMLTableSectionElement; + querySelector(selectors: "td"): HTMLTableDataCellElement; + querySelector(selectors: "template"): HTMLTemplateElement; + querySelector(selectors: "text"): SVGTextElement; + querySelector(selectors: "textpath"): SVGTextPathElement; + querySelector(selectors: "textarea"): HTMLTextAreaElement; + querySelector(selectors: "tfoot"): HTMLTableSectionElement; + querySelector(selectors: "th"): HTMLTableHeaderCellElement; + querySelector(selectors: "thead"): HTMLTableSectionElement; + querySelector(selectors: "title"): HTMLTitleElement; + querySelector(selectors: "tr"): HTMLTableRowElement; + querySelector(selectors: "track"): HTMLTrackElement; + querySelector(selectors: "tspan"): SVGTSpanElement; + querySelector(selectors: "tt"): HTMLElement; + querySelector(selectors: "u"): HTMLElement; + querySelector(selectors: "ul"): HTMLUListElement; + querySelector(selectors: "use"): SVGUseElement; + querySelector(selectors: "var"): HTMLElement; + querySelector(selectors: "video"): HTMLVideoElement; + querySelector(selectors: "view"): SVGViewElement; + querySelector(selectors: "wbr"): HTMLElement; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; + querySelector(selectors: "xmp"): HTMLPreElement; querySelector(selectors: string): Element; + querySelectorAll(selectors: "a"): NodeListOf; + querySelectorAll(selectors: "abbr"): NodeListOf; + querySelectorAll(selectors: "acronym"): NodeListOf; + querySelectorAll(selectors: "address"): NodeListOf; + querySelectorAll(selectors: "applet"): NodeListOf; + querySelectorAll(selectors: "area"): NodeListOf; + querySelectorAll(selectors: "article"): NodeListOf; + querySelectorAll(selectors: "aside"): NodeListOf; + querySelectorAll(selectors: "audio"): NodeListOf; + querySelectorAll(selectors: "b"): NodeListOf; + querySelectorAll(selectors: "base"): NodeListOf; + querySelectorAll(selectors: "basefont"): NodeListOf; + querySelectorAll(selectors: "bdo"): NodeListOf; + querySelectorAll(selectors: "big"): NodeListOf; + querySelectorAll(selectors: "blockquote"): NodeListOf; + querySelectorAll(selectors: "body"): NodeListOf; + querySelectorAll(selectors: "br"): NodeListOf; + querySelectorAll(selectors: "button"): NodeListOf; + querySelectorAll(selectors: "canvas"): NodeListOf; + querySelectorAll(selectors: "caption"): NodeListOf; + querySelectorAll(selectors: "center"): NodeListOf; + querySelectorAll(selectors: "circle"): NodeListOf; + querySelectorAll(selectors: "cite"): NodeListOf; + querySelectorAll(selectors: "clippath"): NodeListOf; + querySelectorAll(selectors: "code"): NodeListOf; + querySelectorAll(selectors: "col"): NodeListOf; + querySelectorAll(selectors: "colgroup"): NodeListOf; + querySelectorAll(selectors: "datalist"): NodeListOf; + querySelectorAll(selectors: "dd"): NodeListOf; + querySelectorAll(selectors: "defs"): NodeListOf; + querySelectorAll(selectors: "del"): NodeListOf; + querySelectorAll(selectors: "desc"): NodeListOf; + querySelectorAll(selectors: "dfn"): NodeListOf; + querySelectorAll(selectors: "dir"): NodeListOf; + querySelectorAll(selectors: "div"): NodeListOf; + querySelectorAll(selectors: "dl"): NodeListOf; + querySelectorAll(selectors: "dt"): NodeListOf; + querySelectorAll(selectors: "ellipse"): NodeListOf; + querySelectorAll(selectors: "em"): NodeListOf; + querySelectorAll(selectors: "embed"): NodeListOf; + querySelectorAll(selectors: "feblend"): NodeListOf; + querySelectorAll(selectors: "fecolormatrix"): NodeListOf; + querySelectorAll(selectors: "fecomponenttransfer"): NodeListOf; + querySelectorAll(selectors: "fecomposite"): NodeListOf; + querySelectorAll(selectors: "feconvolvematrix"): NodeListOf; + querySelectorAll(selectors: "fediffuselighting"): NodeListOf; + querySelectorAll(selectors: "fedisplacementmap"): NodeListOf; + querySelectorAll(selectors: "fedistantlight"): NodeListOf; + querySelectorAll(selectors: "feflood"): NodeListOf; + querySelectorAll(selectors: "fefunca"): NodeListOf; + querySelectorAll(selectors: "fefuncb"): NodeListOf; + querySelectorAll(selectors: "fefuncg"): NodeListOf; + querySelectorAll(selectors: "fefuncr"): NodeListOf; + querySelectorAll(selectors: "fegaussianblur"): NodeListOf; + querySelectorAll(selectors: "feimage"): NodeListOf; + querySelectorAll(selectors: "femerge"): NodeListOf; + querySelectorAll(selectors: "femergenode"): NodeListOf; + querySelectorAll(selectors: "femorphology"): NodeListOf; + querySelectorAll(selectors: "feoffset"): NodeListOf; + querySelectorAll(selectors: "fepointlight"): NodeListOf; + querySelectorAll(selectors: "fespecularlighting"): NodeListOf; + querySelectorAll(selectors: "fespotlight"): NodeListOf; + querySelectorAll(selectors: "fetile"): NodeListOf; + querySelectorAll(selectors: "feturbulence"): NodeListOf; + querySelectorAll(selectors: "fieldset"): NodeListOf; + querySelectorAll(selectors: "figcaption"): NodeListOf; + querySelectorAll(selectors: "figure"): NodeListOf; + querySelectorAll(selectors: "filter"): NodeListOf; + querySelectorAll(selectors: "font"): NodeListOf; + querySelectorAll(selectors: "footer"): NodeListOf; + querySelectorAll(selectors: "foreignobject"): NodeListOf; + querySelectorAll(selectors: "form"): NodeListOf; + querySelectorAll(selectors: "frame"): NodeListOf; + querySelectorAll(selectors: "frameset"): NodeListOf; + querySelectorAll(selectors: "g"): NodeListOf; + querySelectorAll(selectors: "h1"): NodeListOf; + querySelectorAll(selectors: "h2"): NodeListOf; + querySelectorAll(selectors: "h3"): NodeListOf; + querySelectorAll(selectors: "h4"): NodeListOf; + querySelectorAll(selectors: "h5"): NodeListOf; + querySelectorAll(selectors: "h6"): NodeListOf; + querySelectorAll(selectors: "head"): NodeListOf; + querySelectorAll(selectors: "header"): NodeListOf; + querySelectorAll(selectors: "hgroup"): NodeListOf; + querySelectorAll(selectors: "hr"): NodeListOf; + querySelectorAll(selectors: "html"): NodeListOf; + querySelectorAll(selectors: "i"): NodeListOf; + querySelectorAll(selectors: "iframe"): NodeListOf; + querySelectorAll(selectors: "image"): NodeListOf; + querySelectorAll(selectors: "img"): NodeListOf; + querySelectorAll(selectors: "input"): NodeListOf; + querySelectorAll(selectors: "ins"): NodeListOf; + querySelectorAll(selectors: "isindex"): NodeListOf; + querySelectorAll(selectors: "kbd"): NodeListOf; + querySelectorAll(selectors: "keygen"): NodeListOf; + querySelectorAll(selectors: "label"): NodeListOf; + querySelectorAll(selectors: "legend"): NodeListOf; + querySelectorAll(selectors: "li"): NodeListOf; + querySelectorAll(selectors: "line"): NodeListOf; + querySelectorAll(selectors: "lineargradient"): NodeListOf; + querySelectorAll(selectors: "link"): NodeListOf; + querySelectorAll(selectors: "listing"): NodeListOf; + querySelectorAll(selectors: "map"): NodeListOf; + querySelectorAll(selectors: "mark"): NodeListOf; + querySelectorAll(selectors: "marker"): NodeListOf; + querySelectorAll(selectors: "marquee"): NodeListOf; + querySelectorAll(selectors: "mask"): NodeListOf; + querySelectorAll(selectors: "menu"): NodeListOf; + querySelectorAll(selectors: "meta"): NodeListOf; + querySelectorAll(selectors: "metadata"): NodeListOf; + querySelectorAll(selectors: "meter"): NodeListOf; + querySelectorAll(selectors: "nav"): NodeListOf; + querySelectorAll(selectors: "nextid"): NodeListOf; + querySelectorAll(selectors: "nobr"): NodeListOf; + querySelectorAll(selectors: "noframes"): NodeListOf; + querySelectorAll(selectors: "noscript"): NodeListOf; + querySelectorAll(selectors: "object"): NodeListOf; + querySelectorAll(selectors: "ol"): NodeListOf; + querySelectorAll(selectors: "optgroup"): NodeListOf; + querySelectorAll(selectors: "option"): NodeListOf; + querySelectorAll(selectors: "p"): NodeListOf; + querySelectorAll(selectors: "param"): NodeListOf; + querySelectorAll(selectors: "path"): NodeListOf; + querySelectorAll(selectors: "pattern"): NodeListOf; + querySelectorAll(selectors: "picture"): NodeListOf; + querySelectorAll(selectors: "plaintext"): NodeListOf; + querySelectorAll(selectors: "polygon"): NodeListOf; + querySelectorAll(selectors: "polyline"): NodeListOf; + querySelectorAll(selectors: "pre"): NodeListOf; + querySelectorAll(selectors: "progress"): NodeListOf; + querySelectorAll(selectors: "q"): NodeListOf; + querySelectorAll(selectors: "radialgradient"): NodeListOf; + querySelectorAll(selectors: "rect"): NodeListOf; + querySelectorAll(selectors: "rt"): NodeListOf; + querySelectorAll(selectors: "ruby"): NodeListOf; + querySelectorAll(selectors: "s"): NodeListOf; + querySelectorAll(selectors: "samp"): NodeListOf; + querySelectorAll(selectors: "script"): NodeListOf; + querySelectorAll(selectors: "section"): NodeListOf; + querySelectorAll(selectors: "select"): NodeListOf; + querySelectorAll(selectors: "small"): NodeListOf; + querySelectorAll(selectors: "source"): NodeListOf; + querySelectorAll(selectors: "span"): NodeListOf; + querySelectorAll(selectors: "stop"): NodeListOf; + querySelectorAll(selectors: "strike"): NodeListOf; + querySelectorAll(selectors: "strong"): NodeListOf; + querySelectorAll(selectors: "style"): NodeListOf; + querySelectorAll(selectors: "sub"): NodeListOf; + querySelectorAll(selectors: "sup"): NodeListOf; + querySelectorAll(selectors: "svg"): NodeListOf; + querySelectorAll(selectors: "switch"): NodeListOf; + querySelectorAll(selectors: "symbol"): NodeListOf; + querySelectorAll(selectors: "table"): NodeListOf; + querySelectorAll(selectors: "tbody"): NodeListOf; + querySelectorAll(selectors: "td"): NodeListOf; + querySelectorAll(selectors: "template"): NodeListOf; + querySelectorAll(selectors: "text"): NodeListOf; + querySelectorAll(selectors: "textpath"): NodeListOf; + querySelectorAll(selectors: "textarea"): NodeListOf; + querySelectorAll(selectors: "tfoot"): NodeListOf; + querySelectorAll(selectors: "th"): NodeListOf; + querySelectorAll(selectors: "thead"): NodeListOf; + querySelectorAll(selectors: "title"): NodeListOf; + querySelectorAll(selectors: "tr"): NodeListOf; + querySelectorAll(selectors: "track"): NodeListOf; + querySelectorAll(selectors: "tspan"): NodeListOf; + querySelectorAll(selectors: "tt"): NodeListOf; + querySelectorAll(selectors: "u"): NodeListOf; + querySelectorAll(selectors: "ul"): NodeListOf; + querySelectorAll(selectors: "use"): NodeListOf; + querySelectorAll(selectors: "var"): NodeListOf; + querySelectorAll(selectors: "video"): NodeListOf; + querySelectorAll(selectors: "view"): NodeListOf; + querySelectorAll(selectors: "wbr"): NodeListOf; + querySelectorAll(selectors: "x-ms-webview"): NodeListOf; + querySelectorAll(selectors: "xmp"): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -13605,18 +13959,21 @@ interface WindowSessionStorage { interface WindowTimers extends Object, WindowTimersExtension { clearInterval(handle: number): void; clearTimeout(handle: number): void; + setInterval(handler: (...args: any[]) => void, timeout: number): number; setInterval(handler: any, timeout?: any, ...args: any[]): number; + setTimeout(handler: (...args: any[]) => void, timeout: number): number; setTimeout(handler: any, timeout?: any, ...args: any[]): number; } interface WindowTimersExtension { clearImmediate(handle: number): void; - setImmediate(expression: any, ...args: any[]): number; + setImmediate(handler: (...args: any[]) => void): number; + setImmediate(handler: any, ...args: any[]): number; } interface XMLHttpRequestEventTarget { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -13640,6 +13997,13 @@ interface StorageEventInit extends EventInit { storageArea?: Storage; } +interface Canvas2DContextAttributes { + alpha?: boolean; + willReadFrequently?: boolean; + storage?: boolean; + [attribute: string]: boolean | string | undefined; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -13689,6 +14053,177 @@ interface ClipboardEventInit extends EventInit { interface IDBArrayKey extends Array { } +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: AlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: AlgorithmIdentifier; +} + +interface RsaHashedImportParams { + hash: AlgorithmIdentifier; +} + +interface RsaPssParams { + saltLength: number; +} + +interface RsaOaepParams extends Algorithm { + label?: BufferSource; +} + +interface EcdsaParams extends Algorithm { + hash: AlgorithmIdentifier; +} + +interface EcKeyGenParams extends Algorithm { + typedCurve: string; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + typedCurve: string; +} + +interface EcKeyImportParams { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + iv: BufferSource; + additionalData?: BufferSource; + tagLength?: number; +} + +interface AesCfbParams extends Algorithm { + iv: BufferSource; +} + +interface HmacImportParams extends Algorithm { + hash?: AlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: AlgorithmIdentifier; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: AlgorithmIdentifier; + length?: number; +} + +interface DhKeyGenParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhImportKeyParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface ConcatParams extends Algorithm { + hash?: AlgorithmIdentifier; + algorithmId: Uint8Array; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + publicInfo?: Uint8Array; + privateInfo?: Uint8Array; +} + +interface HkdfCtrParams extends Algorithm { + hash: AlgorithmIdentifier; + label: BufferSource; + context: BufferSource; +} + +interface Pbkdf2Params extends Algorithm { + salt: BufferSource; + iterations: number; + hash: AlgorithmIdentifier; +} + +interface RsaOtherPrimesInfo { + r: string; + d: string; + t: string; +} + +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + kid?: string; + x5u?: string; + x5c?: string; + x5t?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -13762,7 +14297,7 @@ declare var msCredentials: MSCredentials; declare var name: string; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; -declare var onabort: (ev: Event) => any; +declare var onabort: (ev: UIEvent) => any; declare var onafterprint: (ev: Event) => any; declare var onbeforeprint: (ev: Event) => any; declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -13912,10 +14447,13 @@ declare function dispatchEvent(evt: Event): boolean; declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; +declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number; declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; declare function clearImmediate(handle: number): void; -declare function setImmediate(expression: any, ...args: any[]): number; +declare function setImmediate(handler: (...args: any[]) => void): number; +declare function setImmediate(handler: any, ...args: any[]): number; declare var sessionStorage: Storage; declare var localStorage: Storage; declare var console: Console; @@ -14058,4 +14596,6 @@ type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; type payloadtype = number; -type IDBValidKey = number | string | Date | IDBArrayKey; \ No newline at end of file +type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; +type MouseWheelEvent = WheelEvent; \ No newline at end of file diff --git a/lib/lib.es2015.promise.d.ts b/lib/lib.es2015.promise.d.ts index 4817121154f..905cc13cba5 100644 --- a/lib/lib.es2015.promise.d.ts +++ b/lib/lib.es2015.promise.d.ts @@ -19,59 +19,149 @@ and limitations under the License. */ interface Promise { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): Promise; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ - catch(onrejected?: (reason: any) => T | PromiseLike): Promise; - catch(onrejected?: (reason: any) => void): Promise; + catch(onrejected: (reason: any) => TResult | PromiseLike): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected: (reason: any) => T | PromiseLike): Promise; } interface PromiseConstructor { - /** - * A reference to the prototype. + /** + * A reference to the prototype. */ readonly prototype: Promise; /** * Creates a new Promise. - * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises + * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | PromiseLike)[]): Promise; + /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject(reason: any): Promise; /** * Creates a new rejected promise for the provided reason. diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 3b9e2d40fce..af497c972fb 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1271,13 +1271,33 @@ declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | P interface PromiseLike { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): PromiseLike; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): PromiseLike; } interface ArrayLike { @@ -1540,7 +1560,7 @@ interface Int8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -1813,7 +1833,7 @@ interface Uint8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2087,7 +2107,7 @@ interface Uint8ClampedArray { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2360,7 +2380,7 @@ interface Int16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2634,7 +2654,7 @@ interface Uint16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2907,7 +2927,7 @@ interface Int32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3180,7 +3200,7 @@ interface Uint32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3453,7 +3473,7 @@ interface Float32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3727,7 +3747,7 @@ interface Float64Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index a4b790b852b..c3b6555d1e8 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -1271,13 +1271,33 @@ declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | P interface PromiseLike { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): PromiseLike; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): PromiseLike; } interface ArrayLike { @@ -1540,7 +1560,7 @@ interface Int8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -1813,7 +1833,7 @@ interface Uint8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2087,7 +2107,7 @@ interface Uint8ClampedArray { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2360,7 +2380,7 @@ interface Int16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2634,7 +2654,7 @@ interface Uint16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2907,7 +2927,7 @@ interface Int32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3180,7 +3200,7 @@ interface Uint32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3453,7 +3473,7 @@ interface Float32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3727,7 +3747,7 @@ interface Float64Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -5118,59 +5138,149 @@ interface Float64ArrayConstructor { */ interface Promise { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): Promise; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ - catch(onrejected?: (reason: any) => T | PromiseLike): Promise; - catch(onrejected?: (reason: any) => void): Promise; + catch(onrejected: (reason: any) => TResult | PromiseLike): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected: (reason: any) => T | PromiseLike): Promise; } interface PromiseConstructor { - /** - * A reference to the prototype. + /** + * A reference to the prototype. */ readonly prototype: Promise; /** * Creates a new Promise. - * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises + * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | PromiseLike)[]): Promise; + /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject(reason: any): Promise; /** * Creates a new rejected promise for the provided reason. @@ -5596,7 +5706,7 @@ interface Float64Array { ///////////////////////////// interface Algorithm { - name?: string; + name: string; } interface AriaRequestEventInit extends EventInit { @@ -6443,6 +6553,7 @@ interface UIEventInit extends EventInit { } interface WebGLContextAttributes { + failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; depth?: boolean; stencil?: boolean; @@ -6511,7 +6622,7 @@ interface ApplicationCache extends EventTarget { oncached: (ev: Event) => any; onchecking: (ev: Event) => any; ondownloading: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onnoupdate: (ev: Event) => any; onobsolete: (ev: Event) => any; onprogress: (ev: ProgressEvent) => any; @@ -7881,7 +7992,7 @@ declare var DeviceRotationRate: { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent { /** - * Sets or gets the URL for the current document. + * Sets or gets the URL for the current document. */ readonly URL: string; /** @@ -7909,7 +8020,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ bgColor: string; /** @@ -7937,19 +8048,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. + * Sets or retrieves a value that indicates the reading order of the object. */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. + * Gets an object representing the document type declaration associated with the current document. */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. + * Gets a reference to the root node of the document. */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. + * Sets or gets the security domain of the document. */ domain: string; /** @@ -7973,7 +8084,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. + * Gets the implementation object of the current document. */ readonly implementation: DOMImplementation; /** @@ -7981,11 +8092,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. + * Gets the date that the page was last modified, if the page supplies one. */ readonly lastModified: string; /** - * Sets or gets the color of the document links. + * Sets or gets the color of the document links. */ linkColor: string; /** @@ -7993,7 +8104,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ links: HTMLCollectionOf; /** - * Contains information about the current URL. + * Contains information about the current URL. */ readonly location: Location; msCSSOMElementFloatMetrics: boolean; @@ -8002,7 +8113,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when the user aborts the download. * @param ev The event. */ - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; /** * Fires when the object is set as the active element. * @param ev The event. @@ -8018,19 +8129,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ onbeforedeactivate: (ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. + /** + * Fires when the object loses the input focus. * @param ev The focus event. */ onblur: (ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. + * Occurs when playback is possible, but would require further buffering. * @param ev The event. */ oncanplay: (ev: Event) => any; oncanplaythrough: (ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. + * Fires when the contents of the object or selection have changed. * @param ev The event. */ onchange: (ev: Event) => any; @@ -8040,7 +8151,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onclick: (ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * Fires when the user clicks the right mouse button in the client area, opening the context menu. * @param ev The mouse event. */ oncontextmenu: (ev: PointerEvent) => any; @@ -8064,12 +8175,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ ondragend: (ev: DragEvent) => any; - /** + /** * Fires on the target element when the user drags the object to a valid drop target. * @param ev The drag event. */ ondragenter: (ev: DragEvent) => any; - /** + /** * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. * @param ev The drag event. */ @@ -8080,23 +8191,23 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ ondragover: (ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. + * Fires on the source object when the user starts to drag a text selection or selected object. * @param ev The event. */ ondragstart: (ev: DragEvent) => any; ondrop: (ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. + * Occurs when the duration attribute is updated. * @param ev The event. */ ondurationchange: (ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. + * Occurs when the media element is reset to its initial state. * @param ev The event. */ onemptied: (ev: Event) => any; /** - * Occurs when the end of playback is reached. + * Occurs when the end of playback is reached. * @param ev The event */ onended: (ev: MediaStreamErrorEvent) => any; @@ -8104,9 +8215,9 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** - * Fires when the object receives focus. + * Fires when the object receives focus. * @param ev The event. */ onfocus: (ev: FocusEvent) => any; @@ -8130,12 +8241,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onkeyup: (ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. + * Fires immediately after the browser loads the object. * @param ev The event. */ onload: (ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. + * Occurs when media data is loaded at the current playback position. * @param ev The event. */ onloadeddata: (ev: Event) => any; @@ -8145,22 +8256,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onloadedmetadata: (ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. + * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ onloadstart: (ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. + * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ onmousedown: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. + * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ onmousemove: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. + * Fires when the user moves the mouse pointer outside the boundaries of the object. * @param ev The mouse event. */ onmouseout: (ev: MouseEvent) => any; @@ -8170,12 +8281,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onmouseover: (ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. + * Fires when the user releases a mouse button while the mouse is over the object. * @param ev The mouse event. */ onmouseup: (ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. + * Fires when the wheel button is rotated. * @param ev The mouse event */ onmousewheel: (ev: WheelEvent) => any; @@ -8197,7 +8308,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (ev: MSPointerEvent) => any; onmspointerup: (ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. * @param ev The event. */ onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; @@ -8212,24 +8323,24 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onpause: (ev: Event) => any; /** - * Occurs when the play method is requested. + * Occurs when the play method is requested. * @param ev The event. */ onplay: (ev: Event) => any; /** - * Occurs when the audio or video has started playing. + * Occurs when the audio or video has started playing. * @param ev The event. */ onplaying: (ev: Event) => any; onpointerlockchange: (ev: Event) => any; onpointerlockerror: (ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. + * Occurs to indicate progress while downloading media data. * @param ev The event. */ onprogress: (ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. + * Occurs when the playback rate is increased or decreased. * @param ev The event. */ onratechange: (ev: Event) => any; @@ -8239,22 +8350,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onreadystatechange: (ev: ProgressEvent) => any; /** - * Fires when the user resets a form. + * Fires when the user resets a form. * @param ev The event. */ onreset: (ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. + * Fires when the user repositions the scroll box in the scroll bar on the object. * @param ev The event. */ onscroll: (ev: UIEvent) => any; /** - * Occurs when the seek operation ends. + * Occurs when the seek operation ends. * @param ev The event. */ onseeked: (ev: Event) => any; /** - * Occurs when the current playback position is moved. + * Occurs when the current playback position is moved. * @param ev The event. */ onseeking: (ev: Event) => any; @@ -8270,7 +8381,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onselectionchange: (ev: Event) => any; onselectstart: (ev: Event) => any; /** - * Occurs when the download has stopped. + * Occurs when the download has stopped. * @param ev The event. */ onstalled: (ev: Event) => any; @@ -8281,7 +8392,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onstop: (ev: Event) => any; onsubmit: (ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. + * Occurs if the load operation has been intentionally halted. * @param ev The event. */ onsuspend: (ev: Event) => any; @@ -8300,7 +8411,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onvolumechange: (ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. + * Occurs when playback stops because the next frame of a video resource is not available. * @param ev The event. */ onwaiting: (ev: Event) => any; @@ -8334,7 +8445,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ title: string; readonly visibilityState: string; - /** + /** * Sets or gets the color of the links that the user has visited. */ vlinkColor: string; @@ -8524,7 +8635,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. * @param root The root element or node to start traversing on. * @param whatToShow The type of nodes or elements to appear in the node list * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. @@ -8533,11 +8644,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. */ createRange(): Range; /** - * Creates a text string from the specified value. + * Creates a text string from the specified value. * @param data String that specifies the nodeValue property of the text node. */ createTextNode(data: string): Text; @@ -8552,7 +8663,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. + * Returns the element for the specified x coordinate and the specified y coordinate. * @param x The x-offset * @param y The y-offset */ @@ -8580,7 +8691,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Returns a reference to the first object with the specified value of the ID or NAME attribute. * @param elementId String that specifies the ID value. Case-insensitive. */ - getElementById(elementId: string): HTMLElement; + getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** * Gets a collection of objects based on the value of the NAME or ID attribute. @@ -8790,7 +8901,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param replace Specifies whether the existing entry for the document is replaced in the history list. */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** + /** * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. * @param commandId Specifies a command identifier. */ @@ -8812,7 +8923,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven queryCommandSupported(commandId: string): boolean; /** * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. */ queryCommandText(commandId: string): string; /** @@ -8828,12 +8939,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. + * Writes one or more HTML expressions to a document in the specified window. * @param content Specifies the text and HTML tags to write. */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; @@ -9055,7 +9166,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec readonly scrollWidth: number; readonly tagName: string; innerHTML: string; - getAttribute(name?: string): string | null; + getAttribute(name: string): string | null; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; @@ -9265,6 +9376,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: string): Element | null; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -9561,12 +9673,12 @@ interface HTMLAnchorElement extends HTMLElement { */ target: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; type: string; urn: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -9668,7 +9780,7 @@ interface HTMLAreaElement extends HTMLElement { */ host: string; /** - * Sets or retrieves the host name part of the location or URL. + * Sets or retrieves the host name part of the location or URL. */ hostname: string; /** @@ -9704,7 +9816,7 @@ interface HTMLAreaElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -9795,7 +9907,7 @@ interface HTMLBodyElement extends HTMLElement { onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; onhashchange: (ev: HashChangeEvent) => any; onload: (ev: Event) => any; @@ -9970,7 +10082,7 @@ interface HTMLButtonElement extends HTMLElement { * Overrides the target attribute on a form element. */ formTarget: string; - /** + /** * Sets or retrieves the name of the object. */ name: string; @@ -9987,7 +10099,7 @@ interface HTMLButtonElement extends HTMLElement { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; - /** + /** * Sets or retrieves the default or selected value of the control. */ value: string; @@ -10024,9 +10136,9 @@ interface HTMLCanvasElement extends HTMLElement { * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); */ - getContext(contextId: "2d"): CanvasRenderingContext2D; - getContext(contextId: "experimental-webgl"): WebGLRenderingContext; - getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext; + getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; + getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; + getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ @@ -10036,7 +10148,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; - toBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, ... arguments: any[]): void; } declare var HTMLCanvasElement: { @@ -10094,7 +10206,7 @@ declare var HTMLDirectoryElement: { interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; /** @@ -10134,7 +10246,7 @@ interface HTMLElement extends Element { readonly offsetParent: Element; readonly offsetTop: number; readonly offsetWidth: number; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onactivate: (ev: UIEvent) => any; onbeforeactivate: (ev: UIEvent) => any; onbeforecopy: (ev: ClipboardEvent) => any; @@ -10162,7 +10274,7 @@ interface HTMLElement extends Element { ondurationchange: (ev: Event) => any; onemptied: (ev: Event) => any; onended: (ev: MediaStreamErrorEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; oninput: (ev: Event) => any; oninvalid: (ev: Event) => any; @@ -10712,7 +10824,7 @@ interface HTMLFrameSetElement extends HTMLElement { * Fires when the object loses the input focus. */ onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** * Fires when the object receives focus. */ @@ -11235,9 +11347,9 @@ interface HTMLInputElement extends HTMLElement { /** * Returns a FileList object on a file type input object. */ - readonly files: FileList; + readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -11957,7 +12069,7 @@ interface HTMLMetaElement extends HTMLElement { */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; } @@ -12206,7 +12318,7 @@ declare var HTMLOptionElement: { create(): HTMLOptionElement; } -interface HTMLOptionsCollection extends HTMLCollection { +interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; @@ -12220,7 +12332,7 @@ declare var HTMLOptionsCollection: { interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; clear: string; @@ -12322,10 +12434,10 @@ interface HTMLScriptElement extends HTMLElement { */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. + * Sets or retrieves the event for which the script is written. */ event: string; - /** + /** * Sets or retrieves the object that is bound to the event script. */ htmlFor: string; @@ -12334,7 +12446,7 @@ interface HTMLScriptElement extends HTMLElement { */ src: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; /** @@ -12355,7 +12467,7 @@ interface HTMLSelectElement extends HTMLElement { autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -12370,7 +12482,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLCollectionOf; + readonly options: HTMLOptionsCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -12381,7 +12493,7 @@ interface HTMLSelectElement extends HTMLElement { selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. + * Sets or retrieves the number of rows in the list box. */ size: number; /** @@ -12407,7 +12519,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. */ add(element: HTMLElement, before?: HTMLElement | number): void; /** @@ -12602,7 +12714,7 @@ interface HTMLTableElement extends HTMLElement { */ border: string; /** - * Sets or retrieves the border color of the object. + * Sets or retrieves the border color of the object. */ borderColor: any; /** @@ -12897,7 +13009,7 @@ declare var HTMLTextAreaElement: { interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; } @@ -13166,7 +13278,7 @@ interface IDBDatabase extends EventTarget { readonly name: string; readonly objectStoreNames: DOMStringList; onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; version: number; onversionchange: (ev: IDBVersionChangeEvent) => any; close(): void; @@ -13269,7 +13381,7 @@ declare var IDBOpenDBRequest: { interface IDBRequest extends EventTarget { readonly error: DOMError; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onsuccess: (ev: Event) => any; readonly readyState: string; readonly result: any; @@ -13291,7 +13403,7 @@ interface IDBTransaction extends EventTarget { readonly mode: string; onabort: (ev: Event) => any; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -13434,7 +13546,7 @@ declare var MSApp: MSApp; interface MSAppAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; start(): void; @@ -13794,7 +13906,7 @@ declare var MSStreamReader: { interface MSWebViewAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; readonly target: MSHTMLWebViewElement; @@ -14330,7 +14442,7 @@ interface Node extends EventTarget { contains(child: Node): boolean; hasAttributes(): boolean; hasChildNodes(): boolean; - insertBefore(newChild: Node, refChild: Node): Node; + insertBefore(newChild: Node, refChild: Node | null): Node; isDefaultNamespace(namespaceURI: string | null): boolean; isEqualNode(arg: Node): boolean; isSameNode(other: Node): boolean; @@ -14339,7 +14451,6 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; - contains(node: Node): boolean; readonly ATTRIBUTE_NODE: number; readonly CDATA_SECTION_NODE: number; readonly COMMENT_NODE: number; @@ -14875,7 +14986,7 @@ declare var RTCDTMFToneChangeEvent: { interface RTCDtlsTransport extends RTCStatsProvider { ondtlsstatechange: ((ev: RTCDtlsTransportStateChangedEvent) => any) | null; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly state: string; readonly transport: RTCIceTransport; getLocalParameters(): RTCDtlsParameters; @@ -14930,7 +15041,7 @@ declare var RTCIceCandidatePairChangedEvent: { interface RTCIceGatherer extends RTCStatsProvider { readonly component: string; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onlocalcandidate: ((ev: RTCIceGathererEvent) => any) | null; createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidate[]; @@ -14989,7 +15100,7 @@ declare var RTCIceTransportStateChangedEvent: { } interface RTCRtpReceiver extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -15009,7 +15120,7 @@ declare var RTCRtpReceiver: { } interface RTCRtpSender extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onssrcconflict: ((ev: RTCSsrcConflictEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack; @@ -15030,7 +15141,7 @@ declare var RTCRtpSender: { } interface RTCSrtpSdesTransport extends EventTarget { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly transport: RTCIceTransport; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -17070,18 +17181,24 @@ declare var StyleSheetPageList: { } interface SubtleCrypto { - decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: string | Algorithm, data: ArrayBufferView): PromiseLike; - encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; } declare var SubtleCrypto: { @@ -17149,7 +17266,7 @@ interface TextTrack extends EventTarget { readonly language: string; mode: any; oncuechange: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; readonly readyState: number; addCue(cue: TextTrackCue): void; @@ -17638,18 +17755,12 @@ interface WebGLRenderingContext { stencilMaskSeparate(face: number, mask: number): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; - texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels?: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; texParameterf(target: number, pname: number, param: number): void; texParameteri(target: number, pname: number, param: number): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels?: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; uniform1f(location: WebGLUniformLocation | null, x: number): void; uniform1fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; uniform1i(location: WebGLUniformLocation | null, x: number): void; @@ -18372,7 +18483,7 @@ interface WebSocket extends EventTarget { readonly bufferedAmount: number; readonly extensions: string; onclose: (ev: CloseEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onmessage: (ev: MessageEvent) => any; onopen: (ev: Event) => any; readonly protocol: string; @@ -18447,7 +18558,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window name: string; readonly navigator: Navigator; offscreenBuffering: string | boolean; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onafterprint: (ev: Event) => any; onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -18563,6 +18674,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly top: Window; readonly window: Window; URL: typeof URL; + Blob: typeof Blob; alert(message?: any): void; blur(): void; cancelAnimationFrame(handle: number): void; @@ -18719,7 +18831,6 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - msCaching: string; onreadystatechange: (ev: ProgressEvent) => any; readonly readyState: number; readonly response: any; @@ -18731,6 +18842,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { timeout: number; readonly upload: XMLHttpRequestUpload; withCredentials: boolean; + msCaching?: string; abort(): void; getAllResponseHeaders(): string; getResponseHeader(header: string): string | null; @@ -18869,7 +18981,7 @@ declare var XSLTProcessor: { } interface AbstractWorker { - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -19028,7 +19140,7 @@ interface LinkStyle { interface MSBaseReader { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -19093,7 +19205,359 @@ interface NavigatorUserMedia { } interface NodeSelector { + querySelector(selectors: "a"): HTMLAnchorElement; + querySelector(selectors: "abbr"): HTMLElement; + querySelector(selectors: "acronym"): HTMLElement; + querySelector(selectors: "address"): HTMLElement; + querySelector(selectors: "applet"): HTMLAppletElement; + querySelector(selectors: "area"): HTMLAreaElement; + querySelector(selectors: "article"): HTMLElement; + querySelector(selectors: "aside"): HTMLElement; + querySelector(selectors: "audio"): HTMLAudioElement; + querySelector(selectors: "b"): HTMLElement; + querySelector(selectors: "base"): HTMLBaseElement; + querySelector(selectors: "basefont"): HTMLBaseFontElement; + querySelector(selectors: "bdo"): HTMLElement; + querySelector(selectors: "big"): HTMLElement; + querySelector(selectors: "blockquote"): HTMLQuoteElement; + querySelector(selectors: "body"): HTMLBodyElement; + querySelector(selectors: "br"): HTMLBRElement; + querySelector(selectors: "button"): HTMLButtonElement; + querySelector(selectors: "canvas"): HTMLCanvasElement; + querySelector(selectors: "caption"): HTMLTableCaptionElement; + querySelector(selectors: "center"): HTMLElement; + querySelector(selectors: "circle"): SVGCircleElement; + querySelector(selectors: "cite"): HTMLElement; + querySelector(selectors: "clippath"): SVGClipPathElement; + querySelector(selectors: "code"): HTMLElement; + querySelector(selectors: "col"): HTMLTableColElement; + querySelector(selectors: "colgroup"): HTMLTableColElement; + querySelector(selectors: "datalist"): HTMLDataListElement; + querySelector(selectors: "dd"): HTMLElement; + querySelector(selectors: "defs"): SVGDefsElement; + querySelector(selectors: "del"): HTMLModElement; + querySelector(selectors: "desc"): SVGDescElement; + querySelector(selectors: "dfn"): HTMLElement; + querySelector(selectors: "dir"): HTMLDirectoryElement; + querySelector(selectors: "div"): HTMLDivElement; + querySelector(selectors: "dl"): HTMLDListElement; + querySelector(selectors: "dt"): HTMLElement; + querySelector(selectors: "ellipse"): SVGEllipseElement; + querySelector(selectors: "em"): HTMLElement; + querySelector(selectors: "embed"): HTMLEmbedElement; + querySelector(selectors: "feblend"): SVGFEBlendElement; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; + querySelector(selectors: "fecomposite"): SVGFECompositeElement; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; + querySelector(selectors: "feflood"): SVGFEFloodElement; + querySelector(selectors: "fefunca"): SVGFEFuncAElement; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; + querySelector(selectors: "feimage"): SVGFEImageElement; + querySelector(selectors: "femerge"): SVGFEMergeElement; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement; + querySelector(selectors: "feoffset"): SVGFEOffsetElement; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement; + querySelector(selectors: "fetile"): SVGFETileElement; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; + querySelector(selectors: "fieldset"): HTMLFieldSetElement; + querySelector(selectors: "figcaption"): HTMLElement; + querySelector(selectors: "figure"): HTMLElement; + querySelector(selectors: "filter"): SVGFilterElement; + querySelector(selectors: "font"): HTMLFontElement; + querySelector(selectors: "footer"): HTMLElement; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement; + querySelector(selectors: "form"): HTMLFormElement; + querySelector(selectors: "frame"): HTMLFrameElement; + querySelector(selectors: "frameset"): HTMLFrameSetElement; + querySelector(selectors: "g"): SVGGElement; + querySelector(selectors: "h1"): HTMLHeadingElement; + querySelector(selectors: "h2"): HTMLHeadingElement; + querySelector(selectors: "h3"): HTMLHeadingElement; + querySelector(selectors: "h4"): HTMLHeadingElement; + querySelector(selectors: "h5"): HTMLHeadingElement; + querySelector(selectors: "h6"): HTMLHeadingElement; + querySelector(selectors: "head"): HTMLHeadElement; + querySelector(selectors: "header"): HTMLElement; + querySelector(selectors: "hgroup"): HTMLElement; + querySelector(selectors: "hr"): HTMLHRElement; + querySelector(selectors: "html"): HTMLHtmlElement; + querySelector(selectors: "i"): HTMLElement; + querySelector(selectors: "iframe"): HTMLIFrameElement; + querySelector(selectors: "image"): SVGImageElement; + querySelector(selectors: "img"): HTMLImageElement; + querySelector(selectors: "input"): HTMLInputElement; + querySelector(selectors: "ins"): HTMLModElement; + querySelector(selectors: "isindex"): HTMLUnknownElement; + querySelector(selectors: "kbd"): HTMLElement; + querySelector(selectors: "keygen"): HTMLElement; + querySelector(selectors: "label"): HTMLLabelElement; + querySelector(selectors: "legend"): HTMLLegendElement; + querySelector(selectors: "li"): HTMLLIElement; + querySelector(selectors: "line"): SVGLineElement; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement; + querySelector(selectors: "link"): HTMLLinkElement; + querySelector(selectors: "listing"): HTMLPreElement; + querySelector(selectors: "map"): HTMLMapElement; + querySelector(selectors: "mark"): HTMLElement; + querySelector(selectors: "marker"): SVGMarkerElement; + querySelector(selectors: "marquee"): HTMLMarqueeElement; + querySelector(selectors: "mask"): SVGMaskElement; + querySelector(selectors: "menu"): HTMLMenuElement; + querySelector(selectors: "meta"): HTMLMetaElement; + querySelector(selectors: "metadata"): SVGMetadataElement; + querySelector(selectors: "meter"): HTMLMeterElement; + querySelector(selectors: "nav"): HTMLElement; + querySelector(selectors: "nextid"): HTMLUnknownElement; + querySelector(selectors: "nobr"): HTMLElement; + querySelector(selectors: "noframes"): HTMLElement; + querySelector(selectors: "noscript"): HTMLElement; + querySelector(selectors: "object"): HTMLObjectElement; + querySelector(selectors: "ol"): HTMLOListElement; + querySelector(selectors: "optgroup"): HTMLOptGroupElement; + querySelector(selectors: "option"): HTMLOptionElement; + querySelector(selectors: "p"): HTMLParagraphElement; + querySelector(selectors: "param"): HTMLParamElement; + querySelector(selectors: "path"): SVGPathElement; + querySelector(selectors: "pattern"): SVGPatternElement; + querySelector(selectors: "picture"): HTMLPictureElement; + querySelector(selectors: "plaintext"): HTMLElement; + querySelector(selectors: "polygon"): SVGPolygonElement; + querySelector(selectors: "polyline"): SVGPolylineElement; + querySelector(selectors: "pre"): HTMLPreElement; + querySelector(selectors: "progress"): HTMLProgressElement; + querySelector(selectors: "q"): HTMLQuoteElement; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement; + querySelector(selectors: "rect"): SVGRectElement; + querySelector(selectors: "rt"): HTMLElement; + querySelector(selectors: "ruby"): HTMLElement; + querySelector(selectors: "s"): HTMLElement; + querySelector(selectors: "samp"): HTMLElement; + querySelector(selectors: "script"): HTMLScriptElement; + querySelector(selectors: "section"): HTMLElement; + querySelector(selectors: "select"): HTMLSelectElement; + querySelector(selectors: "small"): HTMLElement; + querySelector(selectors: "source"): HTMLSourceElement; + querySelector(selectors: "span"): HTMLSpanElement; + querySelector(selectors: "stop"): SVGStopElement; + querySelector(selectors: "strike"): HTMLElement; + querySelector(selectors: "strong"): HTMLElement; + querySelector(selectors: "style"): HTMLStyleElement; + querySelector(selectors: "sub"): HTMLElement; + querySelector(selectors: "sup"): HTMLElement; + querySelector(selectors: "svg"): SVGSVGElement; + querySelector(selectors: "switch"): SVGSwitchElement; + querySelector(selectors: "symbol"): SVGSymbolElement; + querySelector(selectors: "table"): HTMLTableElement; + querySelector(selectors: "tbody"): HTMLTableSectionElement; + querySelector(selectors: "td"): HTMLTableDataCellElement; + querySelector(selectors: "template"): HTMLTemplateElement; + querySelector(selectors: "text"): SVGTextElement; + querySelector(selectors: "textpath"): SVGTextPathElement; + querySelector(selectors: "textarea"): HTMLTextAreaElement; + querySelector(selectors: "tfoot"): HTMLTableSectionElement; + querySelector(selectors: "th"): HTMLTableHeaderCellElement; + querySelector(selectors: "thead"): HTMLTableSectionElement; + querySelector(selectors: "title"): HTMLTitleElement; + querySelector(selectors: "tr"): HTMLTableRowElement; + querySelector(selectors: "track"): HTMLTrackElement; + querySelector(selectors: "tspan"): SVGTSpanElement; + querySelector(selectors: "tt"): HTMLElement; + querySelector(selectors: "u"): HTMLElement; + querySelector(selectors: "ul"): HTMLUListElement; + querySelector(selectors: "use"): SVGUseElement; + querySelector(selectors: "var"): HTMLElement; + querySelector(selectors: "video"): HTMLVideoElement; + querySelector(selectors: "view"): SVGViewElement; + querySelector(selectors: "wbr"): HTMLElement; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; + querySelector(selectors: "xmp"): HTMLPreElement; querySelector(selectors: string): Element; + querySelectorAll(selectors: "a"): NodeListOf; + querySelectorAll(selectors: "abbr"): NodeListOf; + querySelectorAll(selectors: "acronym"): NodeListOf; + querySelectorAll(selectors: "address"): NodeListOf; + querySelectorAll(selectors: "applet"): NodeListOf; + querySelectorAll(selectors: "area"): NodeListOf; + querySelectorAll(selectors: "article"): NodeListOf; + querySelectorAll(selectors: "aside"): NodeListOf; + querySelectorAll(selectors: "audio"): NodeListOf; + querySelectorAll(selectors: "b"): NodeListOf; + querySelectorAll(selectors: "base"): NodeListOf; + querySelectorAll(selectors: "basefont"): NodeListOf; + querySelectorAll(selectors: "bdo"): NodeListOf; + querySelectorAll(selectors: "big"): NodeListOf; + querySelectorAll(selectors: "blockquote"): NodeListOf; + querySelectorAll(selectors: "body"): NodeListOf; + querySelectorAll(selectors: "br"): NodeListOf; + querySelectorAll(selectors: "button"): NodeListOf; + querySelectorAll(selectors: "canvas"): NodeListOf; + querySelectorAll(selectors: "caption"): NodeListOf; + querySelectorAll(selectors: "center"): NodeListOf; + querySelectorAll(selectors: "circle"): NodeListOf; + querySelectorAll(selectors: "cite"): NodeListOf; + querySelectorAll(selectors: "clippath"): NodeListOf; + querySelectorAll(selectors: "code"): NodeListOf; + querySelectorAll(selectors: "col"): NodeListOf; + querySelectorAll(selectors: "colgroup"): NodeListOf; + querySelectorAll(selectors: "datalist"): NodeListOf; + querySelectorAll(selectors: "dd"): NodeListOf; + querySelectorAll(selectors: "defs"): NodeListOf; + querySelectorAll(selectors: "del"): NodeListOf; + querySelectorAll(selectors: "desc"): NodeListOf; + querySelectorAll(selectors: "dfn"): NodeListOf; + querySelectorAll(selectors: "dir"): NodeListOf; + querySelectorAll(selectors: "div"): NodeListOf; + querySelectorAll(selectors: "dl"): NodeListOf; + querySelectorAll(selectors: "dt"): NodeListOf; + querySelectorAll(selectors: "ellipse"): NodeListOf; + querySelectorAll(selectors: "em"): NodeListOf; + querySelectorAll(selectors: "embed"): NodeListOf; + querySelectorAll(selectors: "feblend"): NodeListOf; + querySelectorAll(selectors: "fecolormatrix"): NodeListOf; + querySelectorAll(selectors: "fecomponenttransfer"): NodeListOf; + querySelectorAll(selectors: "fecomposite"): NodeListOf; + querySelectorAll(selectors: "feconvolvematrix"): NodeListOf; + querySelectorAll(selectors: "fediffuselighting"): NodeListOf; + querySelectorAll(selectors: "fedisplacementmap"): NodeListOf; + querySelectorAll(selectors: "fedistantlight"): NodeListOf; + querySelectorAll(selectors: "feflood"): NodeListOf; + querySelectorAll(selectors: "fefunca"): NodeListOf; + querySelectorAll(selectors: "fefuncb"): NodeListOf; + querySelectorAll(selectors: "fefuncg"): NodeListOf; + querySelectorAll(selectors: "fefuncr"): NodeListOf; + querySelectorAll(selectors: "fegaussianblur"): NodeListOf; + querySelectorAll(selectors: "feimage"): NodeListOf; + querySelectorAll(selectors: "femerge"): NodeListOf; + querySelectorAll(selectors: "femergenode"): NodeListOf; + querySelectorAll(selectors: "femorphology"): NodeListOf; + querySelectorAll(selectors: "feoffset"): NodeListOf; + querySelectorAll(selectors: "fepointlight"): NodeListOf; + querySelectorAll(selectors: "fespecularlighting"): NodeListOf; + querySelectorAll(selectors: "fespotlight"): NodeListOf; + querySelectorAll(selectors: "fetile"): NodeListOf; + querySelectorAll(selectors: "feturbulence"): NodeListOf; + querySelectorAll(selectors: "fieldset"): NodeListOf; + querySelectorAll(selectors: "figcaption"): NodeListOf; + querySelectorAll(selectors: "figure"): NodeListOf; + querySelectorAll(selectors: "filter"): NodeListOf; + querySelectorAll(selectors: "font"): NodeListOf; + querySelectorAll(selectors: "footer"): NodeListOf; + querySelectorAll(selectors: "foreignobject"): NodeListOf; + querySelectorAll(selectors: "form"): NodeListOf; + querySelectorAll(selectors: "frame"): NodeListOf; + querySelectorAll(selectors: "frameset"): NodeListOf; + querySelectorAll(selectors: "g"): NodeListOf; + querySelectorAll(selectors: "h1"): NodeListOf; + querySelectorAll(selectors: "h2"): NodeListOf; + querySelectorAll(selectors: "h3"): NodeListOf; + querySelectorAll(selectors: "h4"): NodeListOf; + querySelectorAll(selectors: "h5"): NodeListOf; + querySelectorAll(selectors: "h6"): NodeListOf; + querySelectorAll(selectors: "head"): NodeListOf; + querySelectorAll(selectors: "header"): NodeListOf; + querySelectorAll(selectors: "hgroup"): NodeListOf; + querySelectorAll(selectors: "hr"): NodeListOf; + querySelectorAll(selectors: "html"): NodeListOf; + querySelectorAll(selectors: "i"): NodeListOf; + querySelectorAll(selectors: "iframe"): NodeListOf; + querySelectorAll(selectors: "image"): NodeListOf; + querySelectorAll(selectors: "img"): NodeListOf; + querySelectorAll(selectors: "input"): NodeListOf; + querySelectorAll(selectors: "ins"): NodeListOf; + querySelectorAll(selectors: "isindex"): NodeListOf; + querySelectorAll(selectors: "kbd"): NodeListOf; + querySelectorAll(selectors: "keygen"): NodeListOf; + querySelectorAll(selectors: "label"): NodeListOf; + querySelectorAll(selectors: "legend"): NodeListOf; + querySelectorAll(selectors: "li"): NodeListOf; + querySelectorAll(selectors: "line"): NodeListOf; + querySelectorAll(selectors: "lineargradient"): NodeListOf; + querySelectorAll(selectors: "link"): NodeListOf; + querySelectorAll(selectors: "listing"): NodeListOf; + querySelectorAll(selectors: "map"): NodeListOf; + querySelectorAll(selectors: "mark"): NodeListOf; + querySelectorAll(selectors: "marker"): NodeListOf; + querySelectorAll(selectors: "marquee"): NodeListOf; + querySelectorAll(selectors: "mask"): NodeListOf; + querySelectorAll(selectors: "menu"): NodeListOf; + querySelectorAll(selectors: "meta"): NodeListOf; + querySelectorAll(selectors: "metadata"): NodeListOf; + querySelectorAll(selectors: "meter"): NodeListOf; + querySelectorAll(selectors: "nav"): NodeListOf; + querySelectorAll(selectors: "nextid"): NodeListOf; + querySelectorAll(selectors: "nobr"): NodeListOf; + querySelectorAll(selectors: "noframes"): NodeListOf; + querySelectorAll(selectors: "noscript"): NodeListOf; + querySelectorAll(selectors: "object"): NodeListOf; + querySelectorAll(selectors: "ol"): NodeListOf; + querySelectorAll(selectors: "optgroup"): NodeListOf; + querySelectorAll(selectors: "option"): NodeListOf; + querySelectorAll(selectors: "p"): NodeListOf; + querySelectorAll(selectors: "param"): NodeListOf; + querySelectorAll(selectors: "path"): NodeListOf; + querySelectorAll(selectors: "pattern"): NodeListOf; + querySelectorAll(selectors: "picture"): NodeListOf; + querySelectorAll(selectors: "plaintext"): NodeListOf; + querySelectorAll(selectors: "polygon"): NodeListOf; + querySelectorAll(selectors: "polyline"): NodeListOf; + querySelectorAll(selectors: "pre"): NodeListOf; + querySelectorAll(selectors: "progress"): NodeListOf; + querySelectorAll(selectors: "q"): NodeListOf; + querySelectorAll(selectors: "radialgradient"): NodeListOf; + querySelectorAll(selectors: "rect"): NodeListOf; + querySelectorAll(selectors: "rt"): NodeListOf; + querySelectorAll(selectors: "ruby"): NodeListOf; + querySelectorAll(selectors: "s"): NodeListOf; + querySelectorAll(selectors: "samp"): NodeListOf; + querySelectorAll(selectors: "script"): NodeListOf; + querySelectorAll(selectors: "section"): NodeListOf; + querySelectorAll(selectors: "select"): NodeListOf; + querySelectorAll(selectors: "small"): NodeListOf; + querySelectorAll(selectors: "source"): NodeListOf; + querySelectorAll(selectors: "span"): NodeListOf; + querySelectorAll(selectors: "stop"): NodeListOf; + querySelectorAll(selectors: "strike"): NodeListOf; + querySelectorAll(selectors: "strong"): NodeListOf; + querySelectorAll(selectors: "style"): NodeListOf; + querySelectorAll(selectors: "sub"): NodeListOf; + querySelectorAll(selectors: "sup"): NodeListOf; + querySelectorAll(selectors: "svg"): NodeListOf; + querySelectorAll(selectors: "switch"): NodeListOf; + querySelectorAll(selectors: "symbol"): NodeListOf; + querySelectorAll(selectors: "table"): NodeListOf; + querySelectorAll(selectors: "tbody"): NodeListOf; + querySelectorAll(selectors: "td"): NodeListOf; + querySelectorAll(selectors: "template"): NodeListOf; + querySelectorAll(selectors: "text"): NodeListOf; + querySelectorAll(selectors: "textpath"): NodeListOf; + querySelectorAll(selectors: "textarea"): NodeListOf; + querySelectorAll(selectors: "tfoot"): NodeListOf; + querySelectorAll(selectors: "th"): NodeListOf; + querySelectorAll(selectors: "thead"): NodeListOf; + querySelectorAll(selectors: "title"): NodeListOf; + querySelectorAll(selectors: "tr"): NodeListOf; + querySelectorAll(selectors: "track"): NodeListOf; + querySelectorAll(selectors: "tspan"): NodeListOf; + querySelectorAll(selectors: "tt"): NodeListOf; + querySelectorAll(selectors: "u"): NodeListOf; + querySelectorAll(selectors: "ul"): NodeListOf; + querySelectorAll(selectors: "use"): NodeListOf; + querySelectorAll(selectors: "var"): NodeListOf; + querySelectorAll(selectors: "video"): NodeListOf; + querySelectorAll(selectors: "view"): NodeListOf; + querySelectorAll(selectors: "wbr"): NodeListOf; + querySelectorAll(selectors: "x-ms-webview"): NodeListOf; + querySelectorAll(selectors: "xmp"): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -19181,18 +19645,21 @@ interface WindowSessionStorage { interface WindowTimers extends Object, WindowTimersExtension { clearInterval(handle: number): void; clearTimeout(handle: number): void; + setInterval(handler: (...args: any[]) => void, timeout: number): number; setInterval(handler: any, timeout?: any, ...args: any[]): number; + setTimeout(handler: (...args: any[]) => void, timeout: number): number; setTimeout(handler: any, timeout?: any, ...args: any[]): number; } interface WindowTimersExtension { clearImmediate(handle: number): void; - setImmediate(expression: any, ...args: any[]): number; + setImmediate(handler: (...args: any[]) => void): number; + setImmediate(handler: any, ...args: any[]): number; } interface XMLHttpRequestEventTarget { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -19216,6 +19683,13 @@ interface StorageEventInit extends EventInit { storageArea?: Storage; } +interface Canvas2DContextAttributes { + alpha?: boolean; + willReadFrequently?: boolean; + storage?: boolean; + [attribute: string]: boolean | string | undefined; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -19265,6 +19739,177 @@ interface ClipboardEventInit extends EventInit { interface IDBArrayKey extends Array { } +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: AlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: AlgorithmIdentifier; +} + +interface RsaHashedImportParams { + hash: AlgorithmIdentifier; +} + +interface RsaPssParams { + saltLength: number; +} + +interface RsaOaepParams extends Algorithm { + label?: BufferSource; +} + +interface EcdsaParams extends Algorithm { + hash: AlgorithmIdentifier; +} + +interface EcKeyGenParams extends Algorithm { + typedCurve: string; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + typedCurve: string; +} + +interface EcKeyImportParams { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + iv: BufferSource; + additionalData?: BufferSource; + tagLength?: number; +} + +interface AesCfbParams extends Algorithm { + iv: BufferSource; +} + +interface HmacImportParams extends Algorithm { + hash?: AlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: AlgorithmIdentifier; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: AlgorithmIdentifier; + length?: number; +} + +interface DhKeyGenParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhImportKeyParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface ConcatParams extends Algorithm { + hash?: AlgorithmIdentifier; + algorithmId: Uint8Array; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + publicInfo?: Uint8Array; + privateInfo?: Uint8Array; +} + +interface HkdfCtrParams extends Algorithm { + hash: AlgorithmIdentifier; + label: BufferSource; + context: BufferSource; +} + +interface Pbkdf2Params extends Algorithm { + salt: BufferSource; + iterations: number; + hash: AlgorithmIdentifier; +} + +interface RsaOtherPrimesInfo { + r: string; + d: string; + t: string; +} + +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + kid?: string; + x5u?: string; + x5c?: string; + x5t?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -19338,7 +19983,7 @@ declare var msCredentials: MSCredentials; declare var name: string; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; -declare var onabort: (ev: Event) => any; +declare var onabort: (ev: UIEvent) => any; declare var onafterprint: (ev: Event) => any; declare var onbeforeprint: (ev: Event) => any; declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -19488,10 +20133,13 @@ declare function dispatchEvent(evt: Event): boolean; declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; +declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number; declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; declare function clearImmediate(handle: number): void; -declare function setImmediate(expression: any, ...args: any[]): number; +declare function setImmediate(handler: (...args: any[]) => void): number; +declare function setImmediate(handler: any, ...args: any[]): number; declare var sessionStorage: Storage; declare var localStorage: Storage; declare var console: Console; @@ -19635,6 +20283,8 @@ type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; type payloadtype = number; type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; +type MouseWheelEvent = WheelEvent; ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index cf5ce7e81d8..fcff4b9eacd 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -19,6 +19,10 @@ and limitations under the License. /// IE Worker APIs ///////////////////////////// +interface Algorithm { + name: string; +} + interface EventInit { bubbles?: boolean; cancelable?: boolean; @@ -34,6 +38,10 @@ interface IDBObjectStoreParameters { keyPath?: IDBKeyPath; } +interface KeyAlgorithm { + name?: string; +} + interface EventListener { (evt: Event): void; } @@ -123,6 +131,18 @@ declare var Coordinates: { new(): Coordinates; } +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +} + interface DOMError { readonly name: string; toString(): string; @@ -339,7 +359,7 @@ interface IDBDatabase extends EventTarget { readonly name: string; readonly objectStoreNames: DOMStringList; onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; version: number; onversionchange: (ev: IDBVersionChangeEvent) => any; close(): void; @@ -442,7 +462,7 @@ declare var IDBOpenDBRequest: { interface IDBRequest extends EventTarget { readonly error: DOMError; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onsuccess: (ev: Event) => any; readonly readyState: string; readonly result: any; @@ -464,7 +484,7 @@ interface IDBTransaction extends EventTarget { readonly mode: string; onabort: (ev: Event) => any; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -532,7 +552,7 @@ declare var MSApp: MSApp; interface MSAppAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; start(): void; @@ -681,7 +701,7 @@ interface WebSocket extends EventTarget { readonly bufferedAmount: number; readonly extensions: string; onclose: (ev: CloseEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onmessage: (ev: MessageEvent) => any; onopen: (ev: Event) => any; readonly protocol: string; @@ -724,7 +744,6 @@ declare var Worker: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - msCaching: string; onreadystatechange: (ev: ProgressEvent) => any; readonly readyState: number; readonly response: any; @@ -736,6 +755,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { timeout: number; readonly upload: XMLHttpRequestUpload; withCredentials: boolean; + msCaching?: string; abort(): void; getAllResponseHeaders(): string; getResponseHeader(header: string): string | null; @@ -782,14 +802,14 @@ declare var XMLHttpRequestUpload: { } interface AbstractWorker { - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } interface MSBaseReader { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -835,7 +855,7 @@ interface WindowConsole { interface XMLHttpRequestEventTarget { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -865,7 +885,7 @@ declare var FileReaderSync: { interface WorkerGlobalScope extends EventTarget, WorkerUtils, DedicatedWorkerGlobalScope, WindowConsole { readonly location: WorkerLocation; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly self: WorkerGlobalScope; close(): void; msWriteProfilerMark(profilerMarkName: string): void; @@ -921,8 +941,11 @@ interface WorkerUtils extends Object, WindowBase64 { clearInterval(handle: number): void; clearTimeout(handle: number): void; importScripts(...urls: string[]): void; + setImmediate(handler: (...args: any[]) => void): number; setImmediate(handler: any, ...args: any[]): number; + setInterval(handler: (...args: any[]) => void, timeout: number): number; setInterval(handler: any, timeout?: any, ...args: any[]): number; + setTimeout(handler: (...args: any[]) => void, timeout: number): number; setTimeout(handler: any, timeout?: any, ...args: any[]): number; } @@ -958,6 +981,177 @@ interface ProgressEventInit extends EventInit { interface IDBArrayKey extends Array { } +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: AlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: AlgorithmIdentifier; +} + +interface RsaHashedImportParams { + hash: AlgorithmIdentifier; +} + +interface RsaPssParams { + saltLength: number; +} + +interface RsaOaepParams extends Algorithm { + label?: BufferSource; +} + +interface EcdsaParams extends Algorithm { + hash: AlgorithmIdentifier; +} + +interface EcKeyGenParams extends Algorithm { + typedCurve: string; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + typedCurve: string; +} + +interface EcKeyImportParams { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + iv: BufferSource; + additionalData?: BufferSource; + tagLength?: number; +} + +interface AesCfbParams extends Algorithm { + iv: BufferSource; +} + +interface HmacImportParams extends Algorithm { + hash?: AlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: AlgorithmIdentifier; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: AlgorithmIdentifier; + length?: number; +} + +interface DhKeyGenParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhImportKeyParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface ConcatParams extends Algorithm { + hash?: AlgorithmIdentifier; + algorithmId: Uint8Array; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + publicInfo?: Uint8Array; + privateInfo?: Uint8Array; +} + +interface HkdfCtrParams extends Algorithm { + hash: AlgorithmIdentifier; + label: BufferSource; + context: BufferSource; +} + +interface Pbkdf2Params extends Algorithm { + salt: BufferSource; + iterations: number; + hash: AlgorithmIdentifier; +} + +interface RsaOtherPrimesInfo { + r: string; + d: string; + t: string; +} + +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + kid?: string; + x5u?: string; + x5c?: string; + x5t?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -991,7 +1185,7 @@ interface FunctionStringCallback { (data: string): void; } declare var location: WorkerLocation; -declare var onerror: (ev: Event) => any; +declare var onerror: (ev: ErrorEvent) => any; declare var self: WorkerGlobalScope; declare function close(): void; declare function msWriteProfilerMark(profilerMarkName: string): void; @@ -1006,8 +1200,11 @@ declare function clearImmediate(handle: number): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; declare function importScripts(...urls: string[]): void; +declare function setImmediate(handler: (...args: any[]) => void): number; declare function setImmediate(handler: any, ...args: any[]): number; +declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number; declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; @@ -1017,5 +1214,7 @@ declare var console: Console; declare function addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +type AlgorithmIdentifier = string | Algorithm; type IDBKeyPath = string; -type IDBValidKey = number | string | Date | IDBArrayKey; \ No newline at end of file +type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; \ No newline at end of file diff --git a/lib/tsc.js b/lib/tsc.js index a53870ecffe..1c6d5b8f47a 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -142,6 +142,15 @@ var ts; return -1; } ts.indexOf = indexOf; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0, len = text.length; i < len; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; function countWhere(array, predicate) { var count = 0; if (array) { @@ -169,12 +178,24 @@ var ts; return result; } ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + if (f(item)) { + array[outIndex] = item; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; function map(array, f) { var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result.push(f(v)); } } @@ -193,8 +214,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; if (!contains(result, item, areEqual)) { result.push(item); } @@ -205,8 +226,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var v = array_7[_i]; result += v[prop]; } return result; @@ -500,6 +521,30 @@ var ts; return a < b ? -1 : 1; } ts.compareValues = compareValues; + function compareStrings(a, b, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + if (ignoreCase) { + if (String.prototype.localeCompare) { + var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); + return result < 0 ? -1 : result > 0 ? 1 : 0; + } + a = a.toUpperCase(); + b = b.toUpperCase(); + if (a === b) + return 0; + } + return a < b ? -1 : 1; + } + ts.compareStrings = compareStrings; + function compareStringsCaseInsensitive(a, b) { + return compareStrings(a, b, true); + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } @@ -722,12 +767,220 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; + function removeTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) === ts.directorySeparator) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) !== ts.directorySeparator) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + a = removeTrailingDirectorySeparator(a); + b = removeTrailingDirectorySeparator(b); + var aComponents = getNormalizedPathComponents(a, currentDirectory); + var bComponents = getNormalizedPathComponents(b, currentDirectory); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + if (result !== 0) { + return result; + } + } + return compareValues(aComponents.length, bComponents.length); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + parent = removeTrailingDirectorySeparator(parent); + child = removeTrailingDirectorySeparator(child); + if (parent === child) + return true; + var parentComponents = getNormalizedPathComponents(parent, currentDirectory); + var childComponents = getNormalizedPathComponents(child, currentDirectory); + if (childComponents.length < parentComponents.length) { + return false; + } + for (var i = 0; i < parentComponents.length; i++) { + var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); + if (result !== 0) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; function fileExtensionIs(path, extension) { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsAny(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsAny = fileExtensionIsAny; + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42, 63]; + function getRegularExpressionForWildcard(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + var pattern = ""; + var hasWrittenSubpattern = false; + spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + var spec = specs_1[_i]; + if (!spec) { + continue; + } + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + if (usage !== "exclude" && components[components.length - 1] === "**") { + continue spec; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + var optionalCount = 0; + for (var _a = 0, components_1 = components; _a < components_1.length; _a++) { + var component = components_1[_a]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + continue spec; + } + subpattern += "(/.+?)?"; + hasRecursiveDirectoryWildcard = true; + hasWrittenComponent = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + hasWrittenComponent = true; + } + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + if (hasWrittenSubpattern) { + pattern += "|"; + } + pattern += "(" + subpattern + ")"; + hasWrittenSubpattern = true; + } + if (!pattern) { + return undefined; + } + return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + } + function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var regexFlag = useCaseSensitiveFileNames ? "" : "i"; + var includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag); + var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); + var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var result = []; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + } + return result; + function visitDirectory(path, absolutePath) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; + var name_1 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!extensions || fileExtensionIsAny(name_1, extensions)) && + (!includeFileRegex || includeFileRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + result.push(name_1); + } + } + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var current = directories_1[_b]; + var name_2 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name_2, absoluteName); + } + } + } + } + ts.matchFiles = matchFiles; + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + var basePaths = [path]; + if (includes) { + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + if (isRootedDiskPath(include)) { + var wildcardOffset = indexOfAnyCharCode(include, wildcardCharCodes); + var includeBasePath = wildcardOffset < 0 + ? removeTrailingDirectorySeparator(getDirectoryPath(include)) + : include.substring(0, include.lastIndexOf(ts.directorySeparator, wildcardOffset)); + includeBasePaths.push(includeBasePath); + } + } + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + include: for (var i = 0; i < includeBasePaths.length; i++) { + var includeBasePath = includeBasePaths[i]; + for (var j = 0; j < basePaths.length; j++) { + if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { + continue include; + } + } + basePaths.push(includeBasePath); + } + } + return basePaths; + } function ensureScriptKind(fileName, scriptKind) { return (scriptKind || getScriptKindFromFileName(fileName)) || 3; } @@ -768,6 +1021,36 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i); + } + } + return 0; + } + ts.getExtensionPriority = getExtensionPriority; + function adjustExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 0; + } + else if (extensionPriority < 5) { + return 2; + } + else { + return 5; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + function getNextLowestExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 2; + } + else { + return 5; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { @@ -788,6 +1071,10 @@ var ts; return ext === ".jsx" || ext === ".tsx"; } ts.isJsxOrTsxExtension = isJsxOrTsxExtension; + function changeExtension(path, newExtension) { + return (removeFileExtension(path) + newExtension); + } + ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -858,6 +1145,7 @@ var ts; ts.sys = (function () { function getWScriptSystem() { var fso = new ActiveXObject("Scripting.FileSystemObject"); + var shell = new ActiveXObject("WScript.Shell"); var fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2; var binaryStream = new ActiveXObject("ADODB.Stream"); @@ -912,9 +1200,6 @@ var ts; fileStream.Close(); } } - function getCanonicalPath(path) { - return path.toLowerCase(); - } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -926,30 +1211,19 @@ var ts; var folder = fso.GetFolder(path); return getNames(folder.subfolders); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { + function getAccessibleFileSystemEntries(path) { + try { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; - var name_1 = ts.combinePaths(path, current); - if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { - result.push(name_1); - } - } - var subfolders = getNames(folder.subfolders); - for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { - var current = subfolders_1[_a]; - var name_2 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_2))) { - visitDirectory(name_2); - } - } + var directories = getNames(folder.subfolders); + return { files: files, directories: directories }; } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } return { args: args, @@ -978,7 +1252,7 @@ var ts; return WScript.ScriptFullName; }, getCurrentDirectory: function () { - return new ActiveXObject("WScript.Shell").CurrentDirectory; + return shell.CurrentDirectory; }, getDirectories: getDirectories, readDirectory: readDirectory, @@ -1107,8 +1381,39 @@ var ts; } } } - function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path : path.toLowerCase(); + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var entry = entries_1[_i]; + if (entry === "." || entry === "..") { + continue; + } + var name_3 = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name_3); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } function fileSystemEntryExists(path, entryKind) { try { @@ -1131,38 +1436,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { - var files = _fs.readdirSync(path || ".").sort(); - var directories = []; - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var current = files_2[_i]; - if (current === "." || current === "..") { - continue; - } - var name_3 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_3))) { - var stat = _fs.statSync(name_3); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name_3, extension)) { - result.push(name_3); - } - } - else if (stat.isDirectory()) { - directories.push(name_3); - } - } - } - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var current = directories_1[_a]; - visitDirectory(current); - } - } - } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -1244,6 +1517,16 @@ var ts; } return process.memoryUsage().heapUsed; }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (e) { } + return 0; + }, exit: function (exitCode) { process.exit(exitCode); }, @@ -1275,7 +1558,10 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - readDirectory: ChakraHost.readDirectory, + readDirectory: function (path, extensions, excludes, includes) { + var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, exit: ChakraHost.quit, realpath: realpath }; @@ -1440,7 +1726,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_a_binding_pattern_1187", message: "A parameter property may not be a binding pattern." }, + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, @@ -1456,7 +1742,6 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower_1204", message: "Cannot compile modules into 'es2015' when targeting 'ES5' or lower." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -1511,6 +1796,7 @@ var ts; Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -1781,6 +2067,8 @@ var ts; The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, + Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, + Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1854,6 +2142,8 @@ var ts; Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." }, Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, @@ -2027,7 +2317,6 @@ var ts; types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "property_declarations_can_only_be_used_in_a_ts_file_8014", message: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, @@ -3807,6 +4096,10 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModule(node) { + return node.kind === 225 && (!node.body); + } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || @@ -4194,6 +4487,7 @@ var ts; case 157: return true; } + return false; } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { @@ -4571,6 +4865,14 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isDeclarationOfFunctionExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 218) { + var declaration = s.valueDeclaration; + return declaration.initializer && declaration.initializer.kind === 179; + } + return false; + } + ts.isDeclarationOfFunctionExpression = isDeclarationOfFunctionExpression; function getSpecialPropertyAssignmentKind(expression) { if (!isInJavaScriptFile(expression)) { return 0; @@ -5462,7 +5764,9 @@ var ts; ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; @@ -5776,6 +6080,10 @@ var ts; return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -6159,7 +6467,6 @@ var ts; return visitNodes(cbNodes, node.properties); case 172: return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); case 173: return visitNode(cbNode, node.expression) || @@ -6910,6 +7217,7 @@ var ts; return token === 19 || token === 15 || token === 37 + || token === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunction() { @@ -8417,7 +8725,7 @@ var ts; } var node = createNode(172, expression.pos); node.expression = expression; - node.dotToken = parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } @@ -8605,7 +8913,6 @@ var ts; if (dotToken) { var propertyAccess = createNode(172, expression.pos); propertyAccess.expression = expression; - propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); continue; @@ -9793,7 +10100,12 @@ var ts; else { node.name = parseLiteralNode(true); } - node.body = parseModuleBlock(); + if (token === 15) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { @@ -10729,8 +11041,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -10802,8 +11114,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -10983,7 +11295,8 @@ var ts; return state_1; } else if (node.kind === 225) { - return getModuleInstanceState(node.body); + var body = node.body; + return body ? getModuleInstanceState(body) : 1; } else { return 1; @@ -11352,11 +11665,6 @@ var ts; break; } } - function isNarrowableReference(expr) { - return expr.kind === 69 || - expr.kind === 97 || - expr.kind === 172 && isNarrowableReference(expr.expression); - } function isNarrowingExpression(expr) { switch (expr.kind) { case 69: @@ -11364,7 +11672,7 @@ var ts; case 172: return isNarrowableReference(expr); case 174: - return true; + return hasNarrowableArgument(expr); case 178: return isNarrowingExpression(expr.expression); case 187: @@ -11374,6 +11682,35 @@ var ts; } return false; } + function isNarrowableReference(expr) { + return expr.kind === 69 || + expr.kind === 97 || + expr.kind === 172 && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 172 && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -11382,20 +11719,34 @@ var ts; case 31: case 32: case 33: - if (isNarrowingExpression(expr.left) && (expr.right.kind === 93 || expr.right.kind === 69)) { - return true; - } - if (expr.left.kind === 182 && isNarrowingExpression(expr.left.expression) && expr.right.kind === 9) { - return true; - } - return false; + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91: - return isNarrowingExpression(expr.left); + return isNarrowableOperand(expr.left); case 24: return isNarrowingExpression(expr.right); } return false; } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 178: + return isNarrowableOperand(expr.expression); + case 187: + switch (expr.operatorToken.kind) { + case 56: + return isNarrowableOperand(expr.left); + case 24: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4, @@ -11409,7 +11760,7 @@ var ts; }; } function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 128 ? 256 : 128; + flow.flags |= flow.flags & 256 ? 512 : 256; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { @@ -11434,8 +11785,21 @@ var ts; setFlowNodeReferenced(antecedent); return { flags: flags, - antecedent: antecedent, - expression: expression + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingSwitchStatement(switchStatement)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { @@ -11645,9 +12009,10 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasNonEmptyDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 && c.statements.length; }); - if (!hasNonEmptyDefault) { - addAntecedent(postSwitchLabel, preSwitchCaseFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250; }); + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); } currentBreakTarget = saveBreakTarget; preSwitchCaseFlow = savePreSwitchCaseFlow; @@ -11655,25 +12020,22 @@ var ts; } function bindCaseBlock(node) { var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { - var clause = clauses[i]; - if (clause.statements.length) { - if (currentFlow.flags & 1) { - currentFlow = preSwitchCaseFlow; - } - else { - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, preSwitchCaseFlow); - addAntecedent(preCaseLabel, currentFlow); - currentFlow = finishFlowLabel(preCaseLabel); - } - bind(clause); - if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; } - else { - bind(clause); + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } } @@ -11938,7 +12300,7 @@ var ts; } function hasExportDeclarations(node) { var body = node.kind === 256 ? node : node.body; - if (body.kind === 256 || body.kind === 226) { + if (body && (body.kind === 256 || body.kind === 226)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; if (stat.kind === 236 || stat.kind === 235) { @@ -12458,7 +12820,7 @@ var ts; constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; var funcSymbol = container.locals[constructorFunction.text]; - if (!funcSymbol || !(funcSymbol.flags & 16)) { + if (!funcSymbol || !(funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return; } if (!funcSymbol.members) { @@ -13043,7 +13405,8 @@ var ts; var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if (modulekind || (!compilerOptions.outFile && !compilerOptions.out)) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out)) { return true; } var sourceFiles = host.getSourceFiles(); @@ -13240,7 +13603,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -13296,6 +13660,29 @@ var ts; } return false; } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 || kind === 172) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64, true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); @@ -13338,9 +13725,11 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = moduleSymbol.exports["export="] ? - getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : - resolveSymbol(moduleSymbol.exports["default"]); + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + moduleSymbol : + moduleSymbol.exports["export="] ? + getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : + resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -13391,6 +13780,9 @@ var ts; if (targetSymbol) { var name_10 = specifier.propertyName || specifier.name; if (name_10.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + return moduleSymbol; + } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_10.text); @@ -14739,6 +15131,9 @@ var ts; function isTypeAny(type) { return type && (type.flags & 1) !== 0; } + function isTypeNever(type) { + return type && (type.flags & 134217728) !== 0; + } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); @@ -14990,18 +15385,21 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } - if (declaration.kind === 187) { - return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - if (declaration.kind === 172) { - if (declaration.parent.kind === 187) { - return links.type = checkExpressionCached(declaration.parent.right); - } - } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + var type = undefined; + if (declaration.kind === 187) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + else if (declaration.kind === 172) { + if (declaration.parent.kind === 187) { + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + } if (!popTypeResolution()) { if (symbol.valueDeclaration.type) { type = unknownType; @@ -15089,9 +15487,14 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var type = createObjectType(65536, symbol); - links.type = strictNullChecks && symbol.flags & 536870912 ? - addTypeKind(type, 32) : type; + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + links.type = anyType; + } + else { + var type = createObjectType(65536, symbol); + links.type = strictNullChecks && symbol.flags & 536870912 ? + addTypeKind(type, 32) : type; + } } return links.type; } @@ -16042,7 +16445,7 @@ var ts; } return result; } - function isOptionalParameter(node) { + function isJSDocOptionalParameter(node) { if (node.flags & 134217728) { if (node.type && node.type.kind === 268) { return true; @@ -16057,7 +16460,9 @@ var ts; } } } - if (ts.hasQuestionToken(node)) { + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -16112,7 +16517,7 @@ var ts; if (param.type && param.type.kind === 166) { hasStringLiterals = true; } - if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { minArgumentCount = i - (hasThisParameter ? 1 : 0); } @@ -17109,6 +17514,9 @@ var ts; function isTypeComparableTo(source, target) { return checkTypeComparableTo(source, target, undefined); } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } @@ -18047,8 +18455,10 @@ var ts; function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralType(type) { - return type.flags & 256; + function isStringLiteralUnionType(type) { + return type.flags & 256 ? true : + type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } function isTupleType(type) { return !!(type.flags & 8192); @@ -18778,6 +19188,29 @@ var ts; } return node; } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 249) { + var expr = clause.expression; + return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + } + return undefined; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function filterType(type, f) { + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { @@ -18793,7 +19226,7 @@ var ts; return result; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 256) { + if (flow.flags & 512) { for (var i = visitedFlowStart; i < visitedFlowCount; i++) { if (visitedFlowNodes[i] === flow) { return visitedFlowTypes[i]; @@ -18811,6 +19244,9 @@ var ts; else if (flow.flags & 96) { type = getTypeAtFlowCondition(flow); } + else if (flow.flags & 128) { + type = getTypeAtSwitchClause(flow); + } else if (flow.flags & 12) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; @@ -18831,7 +19267,7 @@ var ts; else { type = declaredType; } - if (flow.flags & 256) { + if (flow.flags & 512) { visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; visitedFlowCount++; @@ -18869,6 +19305,10 @@ var ts; } return type; } + function getTypeAtSwitchClause(flow) { + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { @@ -18929,11 +19369,26 @@ var ts; case 31: case 32: case 33: - if (isNullOrUndefinedLiteral(expr.right)) { - return narrowTypeByNullCheck(type, expr, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (expr.left.kind === 182 && expr.right.kind === 9) { - return narrowTypeByTypeof(type, expr, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + } + if (left.kind === 182 && right.kind === 9) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + } + if (right.kind === 182 && left.kind === 9) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + } + if (left.kind === 172) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + } + if (right.kind === 172) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91: @@ -18943,46 +19398,91 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, expr, assumeTrue) { - var operator = expr.operatorToken.kind; + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(expr.left))) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } var doubleEquals = operator === 30 || operator === 31; var facts = doubleEquals ? assumeTrue ? 65536 : 524288 : - expr.right.kind === 93 ? + literal.kind === 93 ? assumeTrue ? 32768 : 262144 : assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - function narrowTypeByTypeof(type, expr, assumeTrue) { - var left = getReferenceFromExpression(expr.left.expression); - var right = expr.right; - if (!isMatchingReference(reference, left)) { - if (containsMatchingReference(reference, left)) { + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + var target = getReferenceFromExpression(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (expr.operatorToken.kind === 31 || - expr.operatorToken.kind === 33) { + if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } if (assumeTrue && !(type.flags & 16384)) { - var targetType = ts.getProperty(typeofTypesByName, right.text); + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, right.text) || 64 : - ts.getProperty(typeofNEFacts, right.text) || 8192; + ts.getProperty(typeofEQFacts, literal.text) || 64 : + ts.getProperty(typeofNEFacts, literal.text) || 8192; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 || operator === 33) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { @@ -19681,9 +20181,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } - function contextualTypeIsStringLiteralType(type) { - return !!(type.flags & 16384 ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); - } function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } @@ -20450,7 +20947,7 @@ var ts; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { - if (right.text) { + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); } return unknownType; @@ -21370,8 +21867,10 @@ var ts; declaration.kind !== 152 && declaration.kind !== 157 && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = checkExpression(node.expression).symbol; - if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16)) { + var funcSymbol = node.expression.kind === 69 ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return getInferredClassType(funcSymbol); } else if (compilerOptions.noImplicitAny) { @@ -21390,6 +21889,7 @@ var ts; } function checkAssertion(node) { var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); @@ -21473,6 +21973,14 @@ var ts; } return emptyObjectType; } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { @@ -21502,18 +22010,10 @@ var ts; else { types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { - return neverType; + return isAsync ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - if (isAsync) { - var promiseType = createPromiseType(voidType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - return voidType; + return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); @@ -21524,7 +22024,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -21535,17 +22035,7 @@ var ts; reportErrorsFromWidening(func, type); } var widenedType = getWidenedType(type); - if (isAsync) { - var promiseType = createPromiseType(widenedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - else { - return widenedType; - } + return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; @@ -21563,10 +22053,40 @@ var ts; }); return aggregatedTypes; } + function isExhaustiveSwitchStatement(node) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172) { + return false; + } + var type = checkExpression(expr.expression); + if (!(type.flags & 16384)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(propType, switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 32768)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 213 && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasReturnWithNoExpression = !!(func.flags & 32768); + var hasReturnWithNoExpression = functionHasImplicitReturn(func); var hasReturnOfTypeNever = false; ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; @@ -21604,7 +22124,7 @@ var ts; if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !(func.flags & 32768)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 65536; @@ -22115,7 +22635,7 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 126) : rightType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; case 52: return getUnionType([getNonNullableType(leftType), rightType]); case 56: @@ -22215,7 +22735,7 @@ var ts; } function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + if (contextualType && isStringLiteralUnionType(contextualType)) { return getStringLiteralTypeForText(node.text); } return stringType; @@ -22964,7 +23484,6 @@ var ts; } } } - var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { @@ -22989,7 +23508,7 @@ var ts; duplicateFunctionDeclaration = true; } } - else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } if (ts.nodeIsPresent(node.body)) { @@ -23016,7 +23535,7 @@ var ts; error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); }); } - if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !(lastSeenNonAmbientDeclaration.flags & 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -23107,7 +23626,7 @@ var ts; } function checkNonThenableType(type, location, message) { type = getWidenedType(type); - if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) { if (location) { if (!message) { message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; @@ -23119,37 +23638,39 @@ var ts; return type; } function getPromisedType(promise) { - if (promise.flags & 1) { + if (isTypeAny(promise)) { return undefined; } - if ((promise.flags & 4096) && promise.target === tryGetGlobalPromiseType()) { - return promise.typeArguments[0]; + if (promise.flags & 4096) { + if (promise.target === tryGetGlobalPromiseType() + || promise.target === getGlobalPromiseLikeType()) { + return promise.typeArguments[0]; + } } var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (thenFunction && (thenFunction.flags & 1)) { + if (!thenFunction || isTypeAny(thenFunction)) { return undefined; } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : emptyArray; + var thenSignatures = getSignaturesOfType(thenFunction, 0); if (thenSignatures.length === 0) { return undefined; } var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); - if (onfulfilledParameterType.flags & 1) { + if (isTypeAny(onfulfilledParameterType)) { return undefined; } var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); - return valueParameterType; + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { - return getTypeAtPosition(signature, 0); + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; } function getAwaitedType(type) { return checkAwaitedType(type, undefined, undefined); @@ -24691,7 +25212,7 @@ var ts; if (isAmbientExternalModule) { if (ts.isExternalModuleAugmentation(node)) { var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); - if (checkBody) { + if (checkBody && node.body) { for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; checkModuleAugmentationElement(statement, isGlobalAugmentation); @@ -24716,7 +25237,12 @@ var ts; } } } - checkSourceElement(node.body); + if (compilerOptions.noImplicitAny && !node.body) { + reportImplicitAnyError(node, anyType); + } + if (node.body) { + checkSourceElement(node.body); + } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { @@ -26276,7 +26802,10 @@ var ts; return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 142 && (flags & 92) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 142 && (flags & 92) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { return checkGrammarAsyncModifier(node, lastAsync); @@ -27930,21 +28459,26 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body.kind !== 226) { + while (node.body && node.body.kind !== 226) { node = node.body; write("."); writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; + if (node.body) { + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + else { + write(";"); + } } function writeTypeAliasDeclaration(node) { var prevEnclosingDeclaration = enclosingDeclaration; @@ -30245,7 +30779,6 @@ var ts; function createPropertyAccessExpression(expression, name) { var result = ts.createSynthesizedNode(172); result.expression = parenthesizeForAccess(expression); - result.dotToken = ts.createSynthesizedNode(21); result.name = name; return result; } @@ -30291,9 +30824,9 @@ var ts; emitTrailingCommentsOfPosition(node.initializer.pos); emit(node.initializer); } - function isNamespaceExportReference(node) { + function isExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 256; + return !!container; } function isImportedReference(node) { var declaration = resolver.getReferencedImportDeclaration(node); @@ -30301,9 +30834,9 @@ var ts; } function emitShorthandPropertyAssignment(node) { writeTextOfNode(currentText, node.name); - if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isNamespaceExportReference(node.name)) { + if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { write(": "); - emit(node.name); + emitExpressionIdentifier(node.name); } if (languageVersion >= 2 && node.objectAssignmentInitializer) { write(" = "); @@ -30358,7 +30891,10 @@ var ts; return; } emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; + var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; + var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); var shouldEmitSpace = false; if (!indentedBeforeDot) { if (node.expression.kind === 8) { @@ -30376,7 +30912,7 @@ var ts; else { write("."); } - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -30749,7 +31285,6 @@ var ts; synthesizedLHS = ts.createSynthesizedNode(172, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; - synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; write(", "); } @@ -32821,7 +33356,11 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { + var isES6ExportedClass = isES6ExportedDeclaration(node); if (node.kind === 221) { + if (isES6ExportedClass && !(node.flags & 512)) { + write("export "); + } if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -32885,9 +33424,15 @@ var ts; write(";"); } emitEnd(node); - if (node.kind === 221) { + if (node.kind === 221 && !isES6ExportedClass) { emitExportMemberAssignment(node); } + else if (isES6ExportedClass && (node.flags & 512)) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); @@ -33183,10 +33728,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 160) { + if (parameterType && parameterType.kind === 160) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType && parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -33203,9 +33748,15 @@ var ts; } } function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node) && node.type) { - emitSerializedTypeNode(node.type); - return; + if (node && ts.isFunctionLike(node)) { + if (node.type) { + emitSerializedTypeNode(node.type); + return; + } + else if (ts.isAsyncFunctionLike(node)) { + write("Promise"); + return; + } } write("void 0"); } @@ -33338,7 +33889,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225) { + if (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -33379,6 +33930,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); + ts.Debug.assert(node.body !== undefined); if (node.body.kind === 226) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; @@ -34946,13 +35498,9 @@ var ts; ts.emitTime = 0; ts.ioReadTime = 0; ts.ioWriteTime = 0; - var emptyArray = []; - var defaultLibrarySearchPaths = [ - "types/", - "node_modules/", - "node_modules/@types/", - ]; ts.version = "1.9.0"; + var emptyArray = []; + var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { while (true) { var fileName = ts.combinePaths(searchPath, "tsconfig.json"); @@ -35080,6 +35628,10 @@ var ts; return undefined; } var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + return options.typeRoots || + ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(), d); }); + } function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { @@ -35088,35 +35640,34 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); + var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; - if (rootDir !== undefined) { - var effectivePrimarySearchPaths = options.typesSearchPaths || defaultLibrarySearchPaths; - for (var _i = 0, effectivePrimarySearchPaths_1 = effectivePrimarySearchPaths; _i < effectivePrimarySearchPaths_1.length; _i++) { - var searchPath = effectivePrimarySearchPaths_1[_i]; - var primaryPath = ts.combinePaths(rootDir, searchPath); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, primaryPath); - } - var candidate = ts.combinePaths(primaryPath, typeReferenceDirectiveName); + if (typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { @@ -35140,9 +35691,6 @@ var ts; if (containingFile) { initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); } - else { - initialLocationForSecondaryLookup = rootDir; - } if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); @@ -35635,25 +36183,12 @@ var ts; } } } - function getDefaultTypeDirectiveNames(rootPath) { - var localTypes = ts.combinePaths(rootPath, "types"); - var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); - var result = []; - if (ts.sys.directoryExists(localTypes)) { - result = result.concat(ts.sys.getDirectories(localTypes)); - } - if (ts.sys.directoryExists(npmTypes)) { - result = result.concat(ts.sys.getDirectories(npmTypes)); - } - return result; - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { - getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -35666,6 +36201,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; } @@ -35721,19 +36257,26 @@ var ts; } return resolutions; } - function getDefaultTypeDirectiveNames(options, rootFiles, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { if (options.types) { return options.types; } - if (host && host.getDefaultTypeDirectiveNames) { - var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - if (commonRoot) { - return host.getDefaultTypeDirectiveNames(commonRoot); + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + result = result.concat(host.getDirectories(root)); + } } } - return undefined; + return result; } - ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -35770,9 +36313,11 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, undefined); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); } @@ -35835,8 +36380,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = {}; - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var sourceFile = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -35855,10 +36400,9 @@ var ts; (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs) || (oldOptions.rootDir !== options.rootDir) || - (oldOptions.typesSearchPaths !== options.typesSearchPaths) || (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.typesRoot !== options.typesRoot) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; @@ -36150,8 +36694,20 @@ var ts; } break; case 145: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; + var propertyDeclaration = node; + if (propertyDeclaration.modifiers) { + for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 113) { + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + } + } + } + if (checkTypeAnnotation(node.type)) { + return true; + } + break; case 224: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; @@ -36283,9 +36839,12 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, true); + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, true); + } } } } @@ -36432,7 +36991,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_name_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); } if (saveResolution) { resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective; @@ -36597,9 +37156,6 @@ var ts; var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - if (options.module === ts.ModuleKind.ES6 && languageVersion < 2) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); - } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); @@ -36985,8 +37541,13 @@ var ts; } }, { - name: "typesRoot", - type: "string" + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + } }, { name: "types", @@ -37052,6 +37613,10 @@ var ts; }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, + { + name: "disableProjectSizeLimit", + type: "boolean" + }, { name: "strictNullChecks", type: "boolean", @@ -37117,7 +37682,15 @@ var ts; } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { - var values = trimString((value || "")).split(","); + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); switch (opt.element.type) { case "number": return ts.map(values, parseInt); @@ -37174,8 +37747,11 @@ var ts; i++; break; case "list": - options[opt.name] = parseListTypeOption(opt, args[i], errors); - i++; + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } break; default: options[opt.name] = parseCustomTypeOption(opt, args[i], errors); @@ -37267,7 +37843,7 @@ var ts; } return output; } - var IgnoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -37275,66 +37851,57 @@ var ts; var options = ts.extend(existingOptions, compilerOptions); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; - var fileNames = getFileNames(errors); + var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, - errors: errors + errors: errors, + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { - var fileNames = []; + var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { - fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = json["files"]; } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); } } - else { - var filesSeen = {}; - var exclude = []; - if (ts.isArray(json["exclude"])) { - exclude = json["exclude"]; + var includeSpecs; + if (ts.hasProperty(json, "include")) { + if (ts.isArray(json["include"])) { + includeSpecs = json["include"]; } else { - exclude = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - exclude.push(outDir); - } - exclude = ts.map(exclude, function (e) { return ts.getNormalizedAbsolutePath(e, basePath); }); - var supportedExtensions = ts.getSupportedExtensions(options); - ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); - for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; - var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); - for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { - var fileName = filesInDirWithExtension_1[_a]; - if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { - continue; - } - if (IgnoreFileNamePattern.test(fileName)) { - continue; - } - if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { - var baseName = fileName.substr(0, fileName.length - extension.length); - if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { - continue; - } - } - filesSeen[fileName] = true; - fileNames.push(fileName); - } + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); } } - if (ts.hasProperty(json, "excludes") && !ts.hasProperty(json, "exclude")) { + var excludeSpecs; + if (ts.hasProperty(json, "exclude")) { + if (ts.isArray(json["exclude"])) { + excludeSpecs = json["exclude"]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + } + } + else if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - return fileNames; + else { + excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + } + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } + if (fileNames === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; @@ -37416,6 +37983,139 @@ var ts; function trimString(s) { return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var literalFileMap = {}; + var wildcardFileMap = {}; + if (include) { + include = validateSpecs(include, errors, false); + } + if (exclude) { + exclude = validateSpecs(exclude, errors, true); + } + var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var supportedExtensions = ts.getSupportedExtensions(options); + if (fileNames) { + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var file = ts.combinePaths(basePath, fileName); + literalFileMap[keyMapper(file)] = file; + } + } + if (include && include.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + var file = _b[_a]; + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + if (ignoreFileNamePattern.test(file)) { + continue; + } + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + wildcardFileMap[key] = file; + } + } + } + var literalFiles = ts.reduceProperties(literalFileMap, addFileToOutput, []); + var wildcardFiles = ts.reduceProperties(wildcardFileMap, addFileToOutput, []); + wildcardFiles.sort(host.useCaseSensitiveFileNames ? ts.compareStrings : ts.compareStringsCaseInsensitive); + return { + fileNames: literalFiles.concat(wildcardFiles), + wildcardDirectories: wildcardDirectories + }; + } + function validateSpecs(specs, errors, allowTrailingRecursion) { + var validSpecs = []; + for (var _i = 0, specs_2 = specs; _i < specs_2.length; _i++) { + var spec = specs_2[_i]; + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + } + else { + validSpecs.push(spec); + } + } + return validSpecs; + } + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var name_35 = ts.combinePaths(path, file); + if (excludeRegex && excludeRegex.test(name_35)) { + continue; + } + var match = wildcardDirectoryPattern.exec(name_35); + if (match) { + var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); + var flags = watchRecursivePattern.test(name_35) ? 1 : 0; + var existingFlags = ts.getProperty(wildcardDirectories, key); + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1) { + recursiveKeys.push(key); + } + } + } + } + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + for (var i = 0; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + return true; + } + } + return false; + } + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + delete wildcardFiles[lowerPriorityPath]; + } + } + function addFileToOutput(output, file) { + output.push(file); + return output; + } + function caseSensitiveKeyMapper(key) { + return key; + } + function caseInsensitiveKeyMapper(key) { + return key.toLowerCase(); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -37431,8 +38131,8 @@ var ts; return; } var currentDir = ts.sys.getCurrentDirectory(); - for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { - var file = files_4[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var file = files_3[_i]; var filepath = ts.getNormalizedAbsolutePath(file, currentDir); ts.sys.write("TSFILE: " + filepath + ts.sys.newLine); } @@ -38019,10 +38719,10 @@ var ts; function serializeCompilerOptions(options) { var result = {}; var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name_35 in options) { - if (ts.hasProperty(options, name_35)) { - var value = options[name_35]; - switch (name_35) { + for (var name_36 in options) { + if (ts.hasProperty(options, name_36)) { + var value = options[name_36]; + switch (name_36) { case "init": case "watch": case "version": @@ -38030,17 +38730,17 @@ var ts; case "project": break; default: - var optionDefinition = optionsNameMap[name_35.toLowerCase()]; + var optionDefinition = optionsNameMap[name_36.toLowerCase()]; if (optionDefinition) { if (typeof optionDefinition.type === "string") { - result[name_35] = value; + result[name_36] = value; } else { var typeMap = optionDefinition.type; for (var key in typeMap) { if (ts.hasProperty(typeMap, key)) { if (typeMap[key] === value) - result[name_35] = key; + result[name_36] = key; } } } diff --git a/lib/tsserver.js b/lib/tsserver.js index 6565ba47042..bd80f9f800e 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -147,6 +147,15 @@ var ts; return -1; } ts.indexOf = indexOf; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0, len = text.length; i < len; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; function countWhere(array, predicate) { var count = 0; if (array) { @@ -174,12 +183,24 @@ var ts; return result; } ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + if (f(item)) { + array[outIndex] = item; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; function map(array, f) { var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result.push(f(v)); } } @@ -198,8 +219,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; if (!contains(result, item, areEqual)) { result.push(item); } @@ -210,8 +231,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var v = array_7[_i]; result += v[prop]; } return result; @@ -505,6 +526,30 @@ var ts; return a < b ? -1 : 1; } ts.compareValues = compareValues; + function compareStrings(a, b, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + if (ignoreCase) { + if (String.prototype.localeCompare) { + var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); + return result < 0 ? -1 : result > 0 ? 1 : 0; + } + a = a.toUpperCase(); + b = b.toUpperCase(); + if (a === b) + return 0; + } + return a < b ? -1 : 1; + } + ts.compareStrings = compareStrings; + function compareStringsCaseInsensitive(a, b) { + return compareStrings(a, b, true); + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } @@ -727,12 +772,220 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; + function removeTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) === ts.directorySeparator) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) !== ts.directorySeparator) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + a = removeTrailingDirectorySeparator(a); + b = removeTrailingDirectorySeparator(b); + var aComponents = getNormalizedPathComponents(a, currentDirectory); + var bComponents = getNormalizedPathComponents(b, currentDirectory); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + if (result !== 0) { + return result; + } + } + return compareValues(aComponents.length, bComponents.length); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + parent = removeTrailingDirectorySeparator(parent); + child = removeTrailingDirectorySeparator(child); + if (parent === child) + return true; + var parentComponents = getNormalizedPathComponents(parent, currentDirectory); + var childComponents = getNormalizedPathComponents(child, currentDirectory); + if (childComponents.length < parentComponents.length) { + return false; + } + for (var i = 0; i < parentComponents.length; i++) { + var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); + if (result !== 0) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; function fileExtensionIs(path, extension) { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsAny(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsAny = fileExtensionIsAny; + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42, 63]; + function getRegularExpressionForWildcard(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + var pattern = ""; + var hasWrittenSubpattern = false; + spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + var spec = specs_1[_i]; + if (!spec) { + continue; + } + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + if (usage !== "exclude" && components[components.length - 1] === "**") { + continue spec; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + var optionalCount = 0; + for (var _a = 0, components_1 = components; _a < components_1.length; _a++) { + var component = components_1[_a]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + continue spec; + } + subpattern += "(/.+?)?"; + hasRecursiveDirectoryWildcard = true; + hasWrittenComponent = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + hasWrittenComponent = true; + } + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + if (hasWrittenSubpattern) { + pattern += "|"; + } + pattern += "(" + subpattern + ")"; + hasWrittenSubpattern = true; + } + if (!pattern) { + return undefined; + } + return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + } + function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var regexFlag = useCaseSensitiveFileNames ? "" : "i"; + var includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag); + var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); + var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var result = []; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + } + return result; + function visitDirectory(path, absolutePath) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; + var name_1 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!extensions || fileExtensionIsAny(name_1, extensions)) && + (!includeFileRegex || includeFileRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + result.push(name_1); + } + } + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var current = directories_1[_b]; + var name_2 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name_2, absoluteName); + } + } + } + } + ts.matchFiles = matchFiles; + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + var basePaths = [path]; + if (includes) { + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + if (isRootedDiskPath(include)) { + var wildcardOffset = indexOfAnyCharCode(include, wildcardCharCodes); + var includeBasePath = wildcardOffset < 0 + ? removeTrailingDirectorySeparator(getDirectoryPath(include)) + : include.substring(0, include.lastIndexOf(ts.directorySeparator, wildcardOffset)); + includeBasePaths.push(includeBasePath); + } + } + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + include: for (var i = 0; i < includeBasePaths.length; i++) { + var includeBasePath = includeBasePaths[i]; + for (var j = 0; j < basePaths.length; j++) { + if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { + continue include; + } + } + basePaths.push(includeBasePath); + } + } + return basePaths; + } function ensureScriptKind(fileName, scriptKind) { return (scriptKind || getScriptKindFromFileName(fileName)) || 3; } @@ -773,6 +1026,36 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i); + } + } + return 0; + } + ts.getExtensionPriority = getExtensionPriority; + function adjustExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 0; + } + else if (extensionPriority < 5) { + return 2; + } + else { + return 5; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + function getNextLowestExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 2; + } + else { + return 5; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { @@ -793,6 +1076,10 @@ var ts; return ext === ".jsx" || ext === ".tsx"; } ts.isJsxOrTsxExtension = isJsxOrTsxExtension; + function changeExtension(path, newExtension) { + return (removeFileExtension(path) + newExtension); + } + ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -863,6 +1150,7 @@ var ts; ts.sys = (function () { function getWScriptSystem() { var fso = new ActiveXObject("Scripting.FileSystemObject"); + var shell = new ActiveXObject("WScript.Shell"); var fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2; var binaryStream = new ActiveXObject("ADODB.Stream"); @@ -917,9 +1205,6 @@ var ts; fileStream.Close(); } } - function getCanonicalPath(path) { - return path.toLowerCase(); - } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -931,30 +1216,19 @@ var ts; var folder = fso.GetFolder(path); return getNames(folder.subfolders); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { + function getAccessibleFileSystemEntries(path) { + try { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; - var name_1 = ts.combinePaths(path, current); - if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { - result.push(name_1); - } - } - var subfolders = getNames(folder.subfolders); - for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { - var current = subfolders_1[_a]; - var name_2 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_2))) { - visitDirectory(name_2); - } - } + var directories = getNames(folder.subfolders); + return { files: files, directories: directories }; } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } return { args: args, @@ -983,7 +1257,7 @@ var ts; return WScript.ScriptFullName; }, getCurrentDirectory: function () { - return new ActiveXObject("WScript.Shell").CurrentDirectory; + return shell.CurrentDirectory; }, getDirectories: getDirectories, readDirectory: readDirectory, @@ -1112,8 +1386,39 @@ var ts; } } } - function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path : path.toLowerCase(); + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var entry = entries_1[_i]; + if (entry === "." || entry === "..") { + continue; + } + var name_3 = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name_3); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } function fileSystemEntryExists(path, entryKind) { try { @@ -1136,38 +1441,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { - var files = _fs.readdirSync(path || ".").sort(); - var directories = []; - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var current = files_2[_i]; - if (current === "." || current === "..") { - continue; - } - var name_3 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_3))) { - var stat = _fs.statSync(name_3); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name_3, extension)) { - result.push(name_3); - } - } - else if (stat.isDirectory()) { - directories.push(name_3); - } - } - } - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var current = directories_1[_a]; - visitDirectory(current); - } - } - } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -1249,6 +1522,16 @@ var ts; } return process.memoryUsage().heapUsed; }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (e) { } + return 0; + }, exit: function (exitCode) { process.exit(exitCode); }, @@ -1280,7 +1563,10 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - readDirectory: ChakraHost.readDirectory, + readDirectory: function (path, extensions, excludes, includes) { + var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, exit: ChakraHost.quit, realpath: realpath }; @@ -1445,7 +1731,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_a_binding_pattern_1187", message: "A parameter property may not be a binding pattern." }, + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, @@ -1461,7 +1747,6 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower_1204", message: "Cannot compile modules into 'es2015' when targeting 'ES5' or lower." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -1516,6 +1801,7 @@ var ts; Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -1786,6 +2072,8 @@ var ts; The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, + Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, + Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1859,6 +2147,8 @@ var ts; Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." }, Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, @@ -2032,7 +2322,6 @@ var ts; types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "property_declarations_can_only_be_used_in_a_ts_file_8014", message: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, @@ -3861,8 +4150,13 @@ var ts; } }, { - name: "typesRoot", - type: "string" + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + } }, { name: "types", @@ -3928,6 +4222,10 @@ var ts; }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, + { + name: "disableProjectSizeLimit", + type: "boolean" + }, { name: "strictNullChecks", type: "boolean", @@ -3993,7 +4291,15 @@ var ts; } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { - var values = trimString((value || "")).split(","); + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); switch (opt.element.type) { case "number": return ts.map(values, parseInt); @@ -4050,8 +4356,11 @@ var ts; i++; break; case "list": - options[opt.name] = parseListTypeOption(opt, args[i], errors); - i++; + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } break; default: options[opt.name] = parseCustomTypeOption(opt, args[i], errors); @@ -4143,7 +4452,7 @@ var ts; } return output; } - var IgnoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -4151,66 +4460,57 @@ var ts; var options = ts.extend(existingOptions, compilerOptions); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; - var fileNames = getFileNames(errors); + var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, - errors: errors + errors: errors, + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { - var fileNames = []; + var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { - fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = json["files"]; } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); } } - else { - var filesSeen = {}; - var exclude = []; - if (ts.isArray(json["exclude"])) { - exclude = json["exclude"]; + var includeSpecs; + if (ts.hasProperty(json, "include")) { + if (ts.isArray(json["include"])) { + includeSpecs = json["include"]; } else { - exclude = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - exclude.push(outDir); - } - exclude = ts.map(exclude, function (e) { return ts.getNormalizedAbsolutePath(e, basePath); }); - var supportedExtensions = ts.getSupportedExtensions(options); - ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); - for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; - var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); - for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { - var fileName = filesInDirWithExtension_1[_a]; - if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { - continue; - } - if (IgnoreFileNamePattern.test(fileName)) { - continue; - } - if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { - var baseName = fileName.substr(0, fileName.length - extension.length); - if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { - continue; - } - } - filesSeen[fileName] = true; - fileNames.push(fileName); - } + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); } } - if (ts.hasProperty(json, "excludes") && !ts.hasProperty(json, "exclude")) { + var excludeSpecs; + if (ts.hasProperty(json, "exclude")) { + if (ts.isArray(json["exclude"])) { + excludeSpecs = json["exclude"]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + } + } + else if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - return fileNames; + else { + excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + } + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } + if (fileNames === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; @@ -4292,6 +4592,139 @@ var ts; function trimString(s) { return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var literalFileMap = {}; + var wildcardFileMap = {}; + if (include) { + include = validateSpecs(include, errors, false); + } + if (exclude) { + exclude = validateSpecs(exclude, errors, true); + } + var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var supportedExtensions = ts.getSupportedExtensions(options); + if (fileNames) { + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var file = ts.combinePaths(basePath, fileName); + literalFileMap[keyMapper(file)] = file; + } + } + if (include && include.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + var file = _b[_a]; + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + if (ignoreFileNamePattern.test(file)) { + continue; + } + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + wildcardFileMap[key] = file; + } + } + } + var literalFiles = ts.reduceProperties(literalFileMap, addFileToOutput, []); + var wildcardFiles = ts.reduceProperties(wildcardFileMap, addFileToOutput, []); + wildcardFiles.sort(host.useCaseSensitiveFileNames ? ts.compareStrings : ts.compareStringsCaseInsensitive); + return { + fileNames: literalFiles.concat(wildcardFiles), + wildcardDirectories: wildcardDirectories + }; + } + function validateSpecs(specs, errors, allowTrailingRecursion) { + var validSpecs = []; + for (var _i = 0, specs_2 = specs; _i < specs_2.length; _i++) { + var spec = specs_2[_i]; + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + } + else { + validSpecs.push(spec); + } + } + return validSpecs; + } + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var name_5 = ts.combinePaths(path, file); + if (excludeRegex && excludeRegex.test(name_5)) { + continue; + } + var match = wildcardDirectoryPattern.exec(name_5); + if (match) { + var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); + var flags = watchRecursivePattern.test(name_5) ? 1 : 0; + var existingFlags = ts.getProperty(wildcardDirectories, key); + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1) { + recursiveKeys.push(key); + } + } + } + } + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + for (var i = 0; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + return true; + } + } + return false; + } + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + delete wildcardFiles[lowerPriorityPath]; + } + } + function addFileToOutput(output, file) { + output.push(file); + return output; + } + function caseSensitiveKeyMapper(key) { + return key; + } + function caseInsensitiveKeyMapper(key) { + return key.toLowerCase(); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -4572,6 +5005,10 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModule(node) { + return node.kind === 225 && (!node.body); + } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || @@ -4900,9 +5337,9 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_5 = node.name; - if (name_5 && name_5.kind === 140) { - traverse(name_5.expression); + var name_6 = node.name; + if (name_6 && name_6.kind === 140) { + traverse(name_6.expression); return; } } @@ -4959,6 +5396,7 @@ var ts; case 157: return true; } + return false; } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { @@ -5336,6 +5774,14 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isDeclarationOfFunctionExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 218) { + var declaration = s.valueDeclaration; + return declaration.initializer && declaration.initializer.kind === 179; + } + return false; + } + ts.isDeclarationOfFunctionExpression = isDeclarationOfFunctionExpression; function getSpecialPropertyAssignmentKind(expression) { if (!isInJavaScriptFile(expression)) { return 0; @@ -5483,8 +5929,8 @@ var ts; var tag = _b[_a]; if (tag.kind === 275) { var parameterTag = tag; - var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_6.text === parameterName) { + var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_7.text === parameterName) { return parameterTag; } } @@ -6227,7 +6673,9 @@ var ts; ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; @@ -6541,6 +6989,10 @@ var ts; return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -6924,7 +7376,6 @@ var ts; return visitNodes(cbNodes, node.properties); case 172: return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); case 173: return visitNode(cbNode, node.expression) || @@ -7675,6 +8126,7 @@ var ts; return token === 19 || token === 15 || token === 37 + || token === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunction() { @@ -9182,7 +9634,7 @@ var ts; } var node = createNode(172, expression.pos); node.expression = expression; - node.dotToken = parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } @@ -9370,7 +9822,6 @@ var ts; if (dotToken) { var propertyAccess = createNode(172, expression.pos); propertyAccess.expression = expression; - propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); continue; @@ -10414,8 +10865,8 @@ var ts; return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_7 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, undefined); + var name_8 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_8, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -10558,7 +11009,12 @@ var ts; else { node.name = parseLiteralNode(true); } - node.body = parseModuleBlock(); + if (token === 15) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { @@ -11302,8 +11758,8 @@ var ts; if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_8 = jsDocTypeReference.name; - if (name_8.text === "Object") { + var name_9 = jsDocTypeReference.name; + if (name_9.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -11386,13 +11842,13 @@ var ts; var typeParameters = []; typeParameters.pos = scanner.getStartPos(); while (true) { - var name_9 = parseJSDocIdentifierName(); - if (!name_9) { + var name_10 = parseJSDocIdentifierName(); + if (!name_10) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_9.pos); - typeParameter.name = name_9; + var typeParameter = createNode(141, name_10.pos); + typeParameter.name = name_10; finishNode(typeParameter); typeParameters.push(typeParameter); if (token === 24) { @@ -11494,8 +11950,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -11567,8 +12023,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -11748,7 +12204,8 @@ var ts; return state_1; } else if (node.kind === 225) { - return getModuleInstanceState(node.body); + var body = node.body; + return body ? getModuleInstanceState(body) : 1; } else { return 1; @@ -12117,11 +12574,6 @@ var ts; break; } } - function isNarrowableReference(expr) { - return expr.kind === 69 || - expr.kind === 97 || - expr.kind === 172 && isNarrowableReference(expr.expression); - } function isNarrowingExpression(expr) { switch (expr.kind) { case 69: @@ -12129,7 +12581,7 @@ var ts; case 172: return isNarrowableReference(expr); case 174: - return true; + return hasNarrowableArgument(expr); case 178: return isNarrowingExpression(expr.expression); case 187: @@ -12139,6 +12591,35 @@ var ts; } return false; } + function isNarrowableReference(expr) { + return expr.kind === 69 || + expr.kind === 97 || + expr.kind === 172 && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 172 && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -12147,20 +12628,34 @@ var ts; case 31: case 32: case 33: - if (isNarrowingExpression(expr.left) && (expr.right.kind === 93 || expr.right.kind === 69)) { - return true; - } - if (expr.left.kind === 182 && isNarrowingExpression(expr.left.expression) && expr.right.kind === 9) { - return true; - } - return false; + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91: - return isNarrowingExpression(expr.left); + return isNarrowableOperand(expr.left); case 24: return isNarrowingExpression(expr.right); } return false; } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 178: + return isNarrowableOperand(expr.expression); + case 187: + switch (expr.operatorToken.kind) { + case 56: + return isNarrowableOperand(expr.left); + case 24: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4, @@ -12174,7 +12669,7 @@ var ts; }; } function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 128 ? 256 : 128; + flow.flags |= flow.flags & 256 ? 512 : 256; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { @@ -12199,8 +12694,21 @@ var ts; setFlowNodeReferenced(antecedent); return { flags: flags, - antecedent: antecedent, - expression: expression + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingSwitchStatement(switchStatement)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { @@ -12410,9 +12918,10 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasNonEmptyDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 && c.statements.length; }); - if (!hasNonEmptyDefault) { - addAntecedent(postSwitchLabel, preSwitchCaseFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250; }); + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); } currentBreakTarget = saveBreakTarget; preSwitchCaseFlow = savePreSwitchCaseFlow; @@ -12420,25 +12929,22 @@ var ts; } function bindCaseBlock(node) { var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { - var clause = clauses[i]; - if (clause.statements.length) { - if (currentFlow.flags & 1) { - currentFlow = preSwitchCaseFlow; - } - else { - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, preSwitchCaseFlow); - addAntecedent(preCaseLabel, currentFlow); - currentFlow = finishFlowLabel(preCaseLabel); - } - bind(clause); - if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; } - else { - bind(clause); + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } } @@ -12703,7 +13209,7 @@ var ts; } function hasExportDeclarations(node) { var body = node.kind === 256 ? node : node.body; - if (body.kind === 256 || body.kind === 226) { + if (body && (body.kind === 256 || body.kind === 226)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; if (stat.kind === 236 || stat.kind === 235) { @@ -13223,7 +13729,7 @@ var ts; constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; var funcSymbol = container.locals[constructorFunction.text]; - if (!funcSymbol || !(funcSymbol.flags & 16)) { + if (!funcSymbol || !(funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return; } if (!funcSymbol.members) { @@ -13808,7 +14314,8 @@ var ts; var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if (modulekind || (!compilerOptions.outFile && !compilerOptions.out)) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out)) { return true; } var sourceFiles = host.getSourceFiles(); @@ -14005,7 +14512,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -14061,6 +14569,29 @@ var ts; } return false; } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 || kind === 172) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64, true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); @@ -14103,9 +14634,11 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = moduleSymbol.exports["export="] ? - getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : - resolveSymbol(moduleSymbol.exports["default"]); + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + moduleSymbol : + moduleSymbol.exports["export="] ? + getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : + resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -14154,22 +14687,25 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_10 = specifier.propertyName || specifier.name; - if (name_10.text) { + var name_11 = specifier.propertyName || specifier.name; + if (name_11.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + return moduleSymbol; + } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_10.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_11.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_10.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_11.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_10, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_10)); + error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_11)); } return symbol; } @@ -15504,6 +16040,9 @@ var ts; function isTypeAny(type) { return type && (type.flags & 1) !== 0; } + function isTypeNever(type) { + return type && (type.flags & 134217728) !== 0; + } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); @@ -15539,19 +16078,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_11 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_11)) { + var name_12 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_12)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_11); + var text = getTextOfPropertyName(name_12); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_11, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_11)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_12)); return unknownType; } } @@ -15755,18 +16294,21 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } - if (declaration.kind === 187) { - return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - if (declaration.kind === 172) { - if (declaration.parent.kind === 187) { - return links.type = checkExpressionCached(declaration.parent.right); - } - } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + var type = undefined; + if (declaration.kind === 187) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + else if (declaration.kind === 172) { + if (declaration.parent.kind === 187) { + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + } if (!popTypeResolution()) { if (symbol.valueDeclaration.type) { type = unknownType; @@ -15854,9 +16396,14 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var type = createObjectType(65536, symbol); - links.type = strictNullChecks && symbol.flags & 536870912 ? - addTypeKind(type, 32) : type; + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + links.type = anyType; + } + else { + var type = createObjectType(65536, symbol); + links.type = strictNullChecks && symbol.flags & 536870912 ? + addTypeKind(type, 32) : type; + } } return links.type; } @@ -16807,7 +17354,7 @@ var ts; } return result; } - function isOptionalParameter(node) { + function isJSDocOptionalParameter(node) { if (node.flags & 134217728) { if (node.type && node.type.kind === 268) { return true; @@ -16822,7 +17369,9 @@ var ts; } } } - if (ts.hasQuestionToken(node)) { + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -16877,7 +17426,7 @@ var ts; if (param.type && param.type.kind === 166) { hasStringLiterals = true; } - if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { minArgumentCount = i - (hasThisParameter ? 1 : 0); } @@ -17874,6 +18423,9 @@ var ts; function isTypeComparableTo(source, target) { return checkTypeComparableTo(source, target, undefined); } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } @@ -18812,8 +19364,10 @@ var ts; function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralType(type) { - return type.flags & 256; + function isStringLiteralUnionType(type) { + return type.flags & 256 ? true : + type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } function isTupleType(type) { return !!(type.flags & 8192); @@ -19543,6 +20097,29 @@ var ts; } return node; } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 249) { + var expr = clause.expression; + return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + } + return undefined; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function filterType(type, f) { + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { @@ -19558,7 +20135,7 @@ var ts; return result; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 256) { + if (flow.flags & 512) { for (var i = visitedFlowStart; i < visitedFlowCount; i++) { if (visitedFlowNodes[i] === flow) { return visitedFlowTypes[i]; @@ -19576,6 +20153,9 @@ var ts; else if (flow.flags & 96) { type = getTypeAtFlowCondition(flow); } + else if (flow.flags & 128) { + type = getTypeAtSwitchClause(flow); + } else if (flow.flags & 12) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; @@ -19596,7 +20176,7 @@ var ts; else { type = declaredType; } - if (flow.flags & 256) { + if (flow.flags & 512) { visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; visitedFlowCount++; @@ -19634,6 +20214,10 @@ var ts; } return type; } + function getTypeAtSwitchClause(flow) { + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { @@ -19694,11 +20278,26 @@ var ts; case 31: case 32: case 33: - if (isNullOrUndefinedLiteral(expr.right)) { - return narrowTypeByNullCheck(type, expr, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (expr.left.kind === 182 && expr.right.kind === 9) { - return narrowTypeByTypeof(type, expr, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + } + if (left.kind === 182 && right.kind === 9) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + } + if (right.kind === 182 && left.kind === 9) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + } + if (left.kind === 172) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + } + if (right.kind === 172) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91: @@ -19708,46 +20307,91 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, expr, assumeTrue) { - var operator = expr.operatorToken.kind; + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(expr.left))) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } var doubleEquals = operator === 30 || operator === 31; var facts = doubleEquals ? assumeTrue ? 65536 : 524288 : - expr.right.kind === 93 ? + literal.kind === 93 ? assumeTrue ? 32768 : 262144 : assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - function narrowTypeByTypeof(type, expr, assumeTrue) { - var left = getReferenceFromExpression(expr.left.expression); - var right = expr.right; - if (!isMatchingReference(reference, left)) { - if (containsMatchingReference(reference, left)) { + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + var target = getReferenceFromExpression(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (expr.operatorToken.kind === 31 || - expr.operatorToken.kind === 33) { + if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } if (assumeTrue && !(type.flags & 16384)) { - var targetType = ts.getProperty(typeofTypesByName, right.text); + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, right.text) || 64 : - ts.getProperty(typeofNEFacts, right.text) || 8192; + ts.getProperty(typeofEQFacts, literal.text) || 64 : + ts.getProperty(typeofNEFacts, literal.text) || 8192; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 || operator === 33) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { @@ -20316,11 +20960,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_12 = declaration.propertyName || declaration.name; + var name_13 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_12)) { - var text = getTextOfPropertyName(name_12); + !ts.isBindingPattern(name_13)) { + var text = getTextOfPropertyName(name_13); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -20446,9 +21090,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } - function contextualTypeIsStringLiteralType(type) { - return !!(type.flags & 16384 ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); - } function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } @@ -21215,7 +21856,7 @@ var ts; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { - if (right.text) { + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); } return unknownType; @@ -21308,15 +21949,15 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_13 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_13 !== undefined) { - var prop = getPropertyOfType(objectType, name_13); + var name_14 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_14 !== undefined) { + var prop = getPropertyOfType(objectType, name_14); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_13, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_14, symbolToString(objectType.symbol)); return unknownType; } } @@ -22135,8 +22776,10 @@ var ts; declaration.kind !== 152 && declaration.kind !== 157 && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = checkExpression(node.expression).symbol; - if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16)) { + var funcSymbol = node.expression.kind === 69 ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return getInferredClassType(funcSymbol); } else if (compilerOptions.noImplicitAny) { @@ -22155,6 +22798,7 @@ var ts; } function checkAssertion(node) { var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); @@ -22238,6 +22882,14 @@ var ts; } return emptyObjectType; } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { @@ -22267,18 +22919,10 @@ var ts; else { types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { - return neverType; + return isAsync ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - if (isAsync) { - var promiseType = createPromiseType(voidType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - return voidType; + return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); @@ -22289,7 +22933,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -22300,17 +22944,7 @@ var ts; reportErrorsFromWidening(func, type); } var widenedType = getWidenedType(type); - if (isAsync) { - var promiseType = createPromiseType(widenedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - else { - return widenedType; - } + return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; @@ -22328,10 +22962,40 @@ var ts; }); return aggregatedTypes; } + function isExhaustiveSwitchStatement(node) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172) { + return false; + } + var type = checkExpression(expr.expression); + if (!(type.flags & 16384)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(propType, switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 32768)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 213 && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasReturnWithNoExpression = !!(func.flags & 32768); + var hasReturnWithNoExpression = functionHasImplicitReturn(func); var hasReturnOfTypeNever = false; ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; @@ -22369,7 +23033,7 @@ var ts; if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !(func.flags & 32768)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 65536; @@ -22662,14 +23326,14 @@ var ts; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_14 = property.name; - if (name_14.kind === 140) { - checkComputedPropertyName(name_14); + var name_15 = property.name; + if (name_15.kind === 140) { + checkComputedPropertyName(name_15); } - if (isComputedNonLiteralName(name_14)) { + if (isComputedNonLiteralName(name_15)) { return undefined; } - var text = getTextOfPropertyName(name_14); + var text = getTextOfPropertyName(name_15); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -22684,7 +23348,7 @@ var ts; } } else { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_14)); + error(name_15, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_15)); } } else { @@ -22880,7 +23544,7 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 126) : rightType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; case 52: return getUnionType([getNonNullableType(leftType), rightType]); case 56: @@ -22980,7 +23644,7 @@ var ts; } function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + if (contextualType && isStringLiteralUnionType(contextualType)) { return getStringLiteralTypeForText(node.text); } return stringType; @@ -23223,9 +23887,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_15 = _a[_i].name; - if (ts.isBindingPattern(name_15) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_15, parameterName, typePredicate.parameterName)) { + var name_16 = _a[_i].name; + if (ts.isBindingPattern(name_16) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -23253,15 +23917,15 @@ var ts; } function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var name_16 = _a[_i].name; - if (name_16.kind === 69 && - name_16.text === predicateVariableName) { + var name_17 = _a[_i].name; + if (name_17.kind === 69 && + name_17.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_16.kind === 168 || - name_16.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, predicateVariableNode, predicateVariableName)) { + else if (name_17.kind === 168 || + name_17.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_17, predicateVariableNode, predicateVariableName)) { return true; } } @@ -23729,7 +24393,6 @@ var ts; } } } - var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { @@ -23754,7 +24417,7 @@ var ts; duplicateFunctionDeclaration = true; } } - else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } if (ts.nodeIsPresent(node.body)) { @@ -23781,7 +24444,7 @@ var ts; error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); }); } - if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !(lastSeenNonAmbientDeclaration.flags & 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -23872,7 +24535,7 @@ var ts; } function checkNonThenableType(type, location, message) { type = getWidenedType(type); - if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) { if (location) { if (!message) { message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; @@ -23884,37 +24547,39 @@ var ts; return type; } function getPromisedType(promise) { - if (promise.flags & 1) { + if (isTypeAny(promise)) { return undefined; } - if ((promise.flags & 4096) && promise.target === tryGetGlobalPromiseType()) { - return promise.typeArguments[0]; + if (promise.flags & 4096) { + if (promise.target === tryGetGlobalPromiseType() + || promise.target === getGlobalPromiseLikeType()) { + return promise.typeArguments[0]; + } } var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (thenFunction && (thenFunction.flags & 1)) { + if (!thenFunction || isTypeAny(thenFunction)) { return undefined; } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : emptyArray; + var thenSignatures = getSignaturesOfType(thenFunction, 0); if (thenSignatures.length === 0) { return undefined; } var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); - if (onfulfilledParameterType.flags & 1) { + if (isTypeAny(onfulfilledParameterType)) { return undefined; } var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); - return valueParameterType; + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { - return getTypeAtPosition(signature, 0); + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; } function getAwaitedType(type) { return checkAwaitedType(type, undefined, undefined); @@ -24255,8 +24920,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_17 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_17, name_17); + var name_18 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_18, name_18); } } } @@ -24326,8 +24991,8 @@ var ts; } var parent_11 = node.parent.parent; var parentType = getTypeForBindingElementParent(parent_11); - var name_18 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_18)); + var name_19 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_19)); if (parent_11.initializer && property && getParentOfSymbol(property)) { checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); } @@ -25456,7 +26121,7 @@ var ts; if (isAmbientExternalModule) { if (ts.isExternalModuleAugmentation(node)) { var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); - if (checkBody) { + if (checkBody && node.body) { for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; checkModuleAugmentationElement(statement, isGlobalAugmentation); @@ -25481,7 +26146,12 @@ var ts; } } } - checkSourceElement(node.body); + if (compilerOptions.noImplicitAny && !node.body) { + reportImplicitAnyError(node, anyType); + } + if (node.body) { + checkSourceElement(node.body); + } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { @@ -25501,9 +26171,9 @@ var ts; break; case 169: case 218: - var name_19 = node.name; - if (ts.isBindingPattern(name_19)) { - for (var _b = 0, _c = name_19.elements; _b < _c.length; _b++) { + var name_20 = node.name; + if (ts.isBindingPattern(name_20)) { + for (var _b = 0, _c = name_20.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -26338,9 +27008,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_20 = symbol.name; + var name_21 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_20); + var symbol = getPropertyOfType(t, name_21); if (symbol) { symbols_3.push(symbol); } @@ -27041,7 +27711,10 @@ var ts; return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 142 && (flags & 92) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 142 && (flags & 92) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { return checkGrammarAsyncModifier(node, lastAsync); @@ -27285,10 +27958,10 @@ var ts; var SetAccessor = 4; var GetOrSetAccessor = GetAccessor | SetAccessor; var _loop_1 = function(prop) { - var name_21 = prop.name; + var name_22 = prop.name; if (prop.kind === 193 || - name_21.kind === 140) { - checkGrammarComputedPropertyName(name_21); + name_22.kind === 140) { + checkGrammarComputedPropertyName(name_22); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; @@ -27301,8 +27974,8 @@ var ts; var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_21.kind === 8) { - checkGrammarNumericLiteral(name_21); + if (name_22.kind === 8) { + checkGrammarNumericLiteral(name_22); } currentKind = Property; } @@ -27318,7 +27991,7 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_21); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_22); if (effectiveName === undefined) { return "continue"; } @@ -27328,18 +28001,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_21, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_21)); + grammarErrorOnNode(name_22, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_22)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } }; @@ -27357,12 +28030,12 @@ var ts; continue; } var jsxAttr = attr; - var name_22 = jsxAttr.name; - if (!ts.hasProperty(seen, name_22.text)) { - seen[name_22.text] = true; + var name_23 = jsxAttr.name; + if (!ts.hasProperty(seen, name_23.text)) { + seen[name_23.text] = true; } else { - return grammarErrorOnNode(name_22, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_23, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -28425,9 +29098,9 @@ var ts; var count = 0; while (true) { count++; - var name_23 = baseName + "_" + count; - if (!ts.hasProperty(currentIdentifiers, name_23)) { - return name_23; + var name_24 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_24)) { + return name_24; } } } @@ -28695,21 +29368,26 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body.kind !== 226) { + while (node.body && node.body.kind !== 226) { node = node.body; write("."); writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; + if (node.body) { + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + else { + write(";"); + } } function writeTypeAliasDeclaration(node) { var prevEnclosingDeclaration = enclosingDeclaration; @@ -29909,19 +30587,19 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_24 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_24)) { + var name_25 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_25)) { tempFlags |= flags; - return name_24; + return name_25; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_25 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_25)) { - return name_25; + var name_26 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_26)) { + return name_26; } } } @@ -30617,8 +31295,8 @@ var ts; } else if (declaration.kind === 234) { write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_26 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_26); + var name_27 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_27); if (languageVersion === 0 && identifier === "default") { write('["default"]'); } @@ -30671,8 +31349,8 @@ var ts; function emitIdentifier(node) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_27 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_27); + var name_28 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_28); return; } } @@ -31010,7 +31688,6 @@ var ts; function createPropertyAccessExpression(expression, name) { var result = ts.createSynthesizedNode(172); result.expression = parenthesizeForAccess(expression); - result.dotToken = ts.createSynthesizedNode(21); result.name = name; return result; } @@ -31056,9 +31733,9 @@ var ts; emitTrailingCommentsOfPosition(node.initializer.pos); emit(node.initializer); } - function isNamespaceExportReference(node) { + function isExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 256; + return !!container; } function isImportedReference(node) { var declaration = resolver.getReferencedImportDeclaration(node); @@ -31066,9 +31743,9 @@ var ts; } function emitShorthandPropertyAssignment(node) { writeTextOfNode(currentText, node.name); - if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isNamespaceExportReference(node.name)) { + if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { write(": "); - emit(node.name); + emitExpressionIdentifier(node.name); } if (languageVersion >= 2 && node.objectAssignmentInitializer) { write(" = "); @@ -31117,13 +31794,16 @@ var ts; if (languageVersion === 2 && node.expression.kind === 95 && isInAsyncMethodWithSuperInES6(node)) { - var name_28 = ts.createSynthesizedNode(9); - name_28.text = node.name.text; - emitSuperAccessInAsyncMethod(node.expression, name_28); + var name_29 = ts.createSynthesizedNode(9); + name_29.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_29); return; } emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; + var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; + var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); var shouldEmitSpace = false; if (!indentedBeforeDot) { if (node.expression.kind === 8) { @@ -31141,7 +31821,7 @@ var ts; else { write("."); } - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -31514,7 +32194,6 @@ var ts; synthesizedLHS = ts.createSynthesizedNode(172, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; - synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; write(", "); } @@ -32790,12 +33469,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_29 = createTempVariable(0); + var name_30 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_29); - emit(name_29); + tempParameters.push(name_30); + emit(name_30); } else { emit(node.name); @@ -33586,7 +34265,11 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { + var isES6ExportedClass = isES6ExportedDeclaration(node); if (node.kind === 221) { + if (isES6ExportedClass && !(node.flags & 512)) { + write("export "); + } if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -33650,9 +34333,15 @@ var ts; write(";"); } emitEnd(node); - if (node.kind === 221) { + if (node.kind === 221 && !isES6ExportedClass) { emitExportMemberAssignment(node); } + else if (isES6ExportedClass && (node.flags & 512)) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); @@ -33948,10 +34637,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 160) { + if (parameterType && parameterType.kind === 160) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType && parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -33968,9 +34657,15 @@ var ts; } } function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node) && node.type) { - emitSerializedTypeNode(node.type); - return; + if (node && ts.isFunctionLike(node)) { + if (node.type) { + emitSerializedTypeNode(node.type); + return; + } + else if (ts.isAsyncFunctionLike(node)) { + write("Promise"); + return; + } } write("void 0"); } @@ -34103,7 +34798,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225) { + if (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -34144,6 +34839,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); + ts.Debug.assert(node.body !== undefined); if (node.body.kind === 226) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; @@ -34523,8 +35219,8 @@ var ts; else { for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_30 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_30] || (exportSpecifiers[name_30] = [])).push(specifier); + var name_31 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_31] || (exportSpecifiers[name_31] = [])).push(specifier); } } break; @@ -34562,9 +35258,9 @@ var ts; } function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { if (emitRelativePathAsModuleName) { - var name_31 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_31) { - return "\"" + name_31 + "\""; + var name_32 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_32) { + return "\"" + name_32 + "\""; } } var moduleName = ts.getExternalModuleName(importNode); @@ -34710,11 +35406,11 @@ var ts; var seen = {}; for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_32 = local.kind === 69 + var name_33 = local.kind === 69 ? local : local.name; - if (name_32) { - var text = ts.unescapeIdentifier(name_32.text); + if (name_33) { + var text = ts.unescapeIdentifier(name_33.text); if (ts.hasProperty(seen, text)) { continue; } @@ -34793,15 +35489,15 @@ var ts; } if (node.kind === 218 || node.kind === 169) { if (shouldHoistVariable(node, false)) { - var name_33 = node.name; - if (name_33.kind === 69) { + var name_34 = node.name; + if (name_34.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_33); + hoistedVars.push(name_34); } else { - ts.forEachChild(name_33, visit); + ts.forEachChild(name_34, visit); } } return; @@ -35711,13 +36407,9 @@ var ts; ts.emitTime = 0; ts.ioReadTime = 0; ts.ioWriteTime = 0; - var emptyArray = []; - var defaultLibrarySearchPaths = [ - "types/", - "node_modules/", - "node_modules/@types/", - ]; ts.version = "1.9.0"; + var emptyArray = []; + var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { while (true) { var fileName = ts.combinePaths(searchPath, "tsconfig.json"); @@ -35845,6 +36537,10 @@ var ts; return undefined; } var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + return options.typeRoots || + ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(), d); }); + } function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { @@ -35853,35 +36549,34 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); + var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; - if (rootDir !== undefined) { - var effectivePrimarySearchPaths = options.typesSearchPaths || defaultLibrarySearchPaths; - for (var _i = 0, effectivePrimarySearchPaths_1 = effectivePrimarySearchPaths; _i < effectivePrimarySearchPaths_1.length; _i++) { - var searchPath = effectivePrimarySearchPaths_1[_i]; - var primaryPath = ts.combinePaths(rootDir, searchPath); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, primaryPath); - } - var candidate = ts.combinePaths(primaryPath, typeReferenceDirectiveName); + if (typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { @@ -35905,9 +36600,6 @@ var ts; if (containingFile) { initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); } - else { - initialLocationForSecondaryLookup = rootDir; - } if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); @@ -36400,25 +37092,12 @@ var ts; } } } - function getDefaultTypeDirectiveNames(rootPath) { - var localTypes = ts.combinePaths(rootPath, "types"); - var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); - var result = []; - if (ts.sys.directoryExists(localTypes)) { - result = result.concat(ts.sys.getDirectories(localTypes)); - } - if (ts.sys.directoryExists(npmTypes)) { - result = result.concat(ts.sys.getDirectories(npmTypes)); - } - return result; - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { - getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -36431,6 +37110,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; } @@ -36473,32 +37153,39 @@ var ts; var resolutions = []; var cache = {}; for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_34 = names_1[_i]; + var name_35 = names_1[_i]; var result = void 0; - if (ts.hasProperty(cache, name_34)) { - result = cache[name_34]; + if (ts.hasProperty(cache, name_35)) { + result = cache[name_35]; } else { - result = loader(name_34, containingFile); - cache[name_34] = result; + result = loader(name_35, containingFile); + cache[name_35] = result; } resolutions.push(result); } return resolutions; } - function getDefaultTypeDirectiveNames(options, rootFiles, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { if (options.types) { return options.types; } - if (host && host.getDefaultTypeDirectiveNames) { - var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - if (commonRoot) { - return host.getDefaultTypeDirectiveNames(commonRoot); + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + result = result.concat(host.getDirectories(root)); + } } } - return undefined; + return result; } - ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -36535,9 +37222,11 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, undefined); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); } @@ -36600,8 +37289,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = {}; - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var sourceFile = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -36620,10 +37309,9 @@ var ts; (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs) || (oldOptions.rootDir !== options.rootDir) || - (oldOptions.typesSearchPaths !== options.typesSearchPaths) || (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.typesRoot !== options.typesRoot) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; @@ -36915,8 +37603,20 @@ var ts; } break; case 145: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; + var propertyDeclaration = node; + if (propertyDeclaration.modifiers) { + for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 113) { + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + } + } + } + if (checkTypeAnnotation(node.type)) { + return true; + } + break; case 224: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; @@ -37048,9 +37748,12 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, true); + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, true); + } } } } @@ -37197,7 +37900,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_name_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); } if (saveResolution) { resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective; @@ -37362,9 +38065,6 @@ var ts; var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - if (options.module === ts.ModuleKind.ES6 && languageVersion < 2) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); - } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); @@ -38069,10 +38769,10 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_35 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_35); + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_35); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -38083,14 +38783,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_35); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_35, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -38220,622 +38920,539 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile, compilerOptions) { - if (ts.isSourceFileJavaScript(sourceFile)) { - return getJsNavigationBarItems(sourceFile, compilerOptions); + function getNavigationBarItems(sourceFile) { + curSourceFile = sourceFile; + var result = ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + var curSourceFile; + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); } - return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); - function getIndent(node) { - var indent = 1; - var current = node.parent; - while (current) { - switch (current.kind) { - case 225: - do { - current = current.parent; - } while (current.kind === 225); - case 221: - case 224: - case 222: - case 220: - indent++; + else { + parent.children = [child]; + } + } + var parentsStack = []; + var parent; + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + parentsStack.push(parent); + parent = navNode; + } + function endNode() { + if (parent.children) { + mergeChildren(parent.children); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + function addChildrenRecursively(node) { + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 148: + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } } - current = current.parent; - } - return indent; - } - function getChildNodes(nodes) { - var childNodes = []; - function visit(node) { - switch (node.kind) { - case 200: - ts.forEach(node.declarationList.declarations, visit); - break; - case 167: - case 168: - ts.forEach(node.elements, visit); - break; - case 236: - if (node.exportClause) { - ts.forEach(node.exportClause.elements, visit); + break; + case 147: + case 149: + case 150: + case 146: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 145: + case 144: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 231: + var importClause = node; + if (importClause.name) { + addLeafNode(importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 232) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); } - break; - case 230: - var importClause = node.importClause; - if (importClause) { - if (importClause.name) { - childNodes.push(importClause); - } - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232) { - childNodes.push(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, visit); - } - } - } - break; - case 169: - case 218: - if (ts.isBindingPattern(node.name)) { - visit(node.name); - break; - } - case 221: - case 224: - case 222: - case 225: - case 220: - case 229: - case 234: - case 238: - case 223: - childNodes.push(node); - break; + } } - } - ts.forEach(nodes, visit); - return sortNodes(childNodes); - } - function getTopLevelNodes(node) { - var topLevelNodes = []; - topLevelNodes.push(node); - addTopLevelNodes(node.statements, topLevelNodes); - return topLevelNodes; - } - function sortNodes(nodes) { - return nodes.slice(0).sort(function (n1, n2) { - if (n1.name && n2.name) { - return localeCompareFix(ts.getPropertyNameForPropertyNameNode(n1.name), ts.getPropertyNameForPropertyNameNode(n2.name)); + break; + case 169: + case 218: + var decl = node; + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } - else if (n1.name) { - return 1; - } - else if (n2.name) { - return -1; + else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { + addChildrenRecursively(decl.initializer); } else { - return n1.kind - n2.kind; + addNodeWithRecursiveChild(decl, decl.initializer); } - }); - function localeCompareFix(a, b) { - var cmp = a.toLowerCase().localeCompare(b.toLowerCase()); - if (cmp !== 0) - return cmp; - return a < b ? 1 : a > b ? -1 : 0; - } - } - function addTopLevelNodes(nodes, topLevelNodes) { - nodes = sortNodes(nodes); - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; - switch (node.kind) { - case 221: - topLevelNodes.push(node); - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 147 || member.kind === 148) { - if (member.body) { - if (hasNamedFunctionDeclarations(member.body.statements)) { - topLevelNodes.push(member); - } - addTopLevelNodes(member.body.statements, topLevelNodes); - } + break; + case 180: + case 220: + case 179: + addNodeWithRecursiveChild(node, node.body); + break; + case 224: + startNode(node); + for (var _d = 0, _e = node.members; _d < _e.length; _d++) { + var member = _e[_d]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 221: + case 192: + case 222: + startNode(node); + for (var _f = 0, _g = node.members; _f < _g.length; _f++) { + var member = _g[_f]; + addChildrenRecursively(member); + } + endNode(); + break; + case 225: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 238: + case 229: + case 153: + case 151: + case 152: + case 223: + addLeafNode(node); + break; + default: + if (node.jsDocComments) { + for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { + var jsDocComment = _j[_h]; + for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { + var tag = _l[_k]; + if (tag.kind === 279) { + addLeafNode(tag); } } - break; - case 224: - case 222: - case 223: - topLevelNodes.push(node); - break; - case 225: - var moduleDeclaration = node; - topLevelNodes.push(node); - addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); - break; - case 220: - var functionDeclaration = node; - if (isTopLevelFunctionDeclaration(functionDeclaration)) { - topLevelNodes.push(node); - addTopLevelNodes(functionDeclaration.body.statements, topLevelNodes); - } - break; + } } - } + ts.forEachChild(node, addChildrenRecursively); } - function hasNamedFunctionDeclarations(nodes) { - for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { - var s = nodes_5[_i]; - if (s.kind === 220 && !isEmpty(s.name.text)) { + } + function mergeChildren(children) { + var nameToItems = {}; + ts.filterMutate(children, function (child) { + var decl = child.node; + var name = decl.name && nodeText(decl.name); + if (!name) { + return true; + } + var itemsWithSameName = ts.getProperty(nameToItems, name); + if (!itemsWithSameName) { + nameToItems[name] = child; + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child)) { + return false; + } + nameToItems[name] = [itemWithSameName, child]; + return true; + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); return true; } + return false; } - return false; - } - function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 220) { - if (functionDeclaration.body && functionDeclaration.body.kind === 199) { - if (hasNamedFunctionDeclarations(functionDeclaration.body.statements)) { - return true; - } - if (!ts.isFunctionBlock(functionDeclaration.parent)) { - return true; - } - else { - var grandParentKind = functionDeclaration.parent.parent.kind; - if (grandParentKind === 147 || - grandParentKind === 148) { - return true; - } - } + }); + function shouldReallyMerge(a, b) { + return a.kind === b.kind && (a.kind !== 225 || areSameModule(a, b)); + function areSameModule(a, b) { + if (a.body.kind !== b.body.kind) { + return false; } - } - return false; - } - function getItemsWorker(nodes, createItem) { - var items = []; - var keyToItem = {}; - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var child = nodes_6[_i]; - var item = createItem(child); - if (item !== undefined) { - if (item.text.length > 0) { - var key = item.text + "-" + item.kind + "-" + item.indent; - var itemWithSameName = keyToItem[key]; - if (itemWithSameName) { - merge(itemWithSameName, item); - } - else { - keyToItem[key] = item; - items.push(item); - } - } + if (a.body.kind !== 225) { + return true; } + return areSameModule(a.body, b.body); } - return items; } function merge(target, source) { - ts.addRange(target.spans, source.spans); - if (source.childItems) { - if (!target.childItems) { - target.childItems = []; - } - outer: for (var _i = 0, _a = source.childItems; _i < _a.length; _i++) { - var sourceChild = _a[_i]; - for (var _b = 0, _c = target.childItems; _b < _c.length; _b++) { - var targetChild = _c[_b]; - if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) { - merge(targetChild, sourceChild); - continue outer; - } - } - target.childItems.push(sourceChild); - } + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); + } + var _a; + } + } + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); + if (name1 && name2) { + var cmp = localeCompareFix(name1, name2); + return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + else { + return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + } + var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + for (var i = 0; i < Math.min(a.length, b.length); i++) { + var chA = a.charAt(i), chB = b.charAt(i); + if (chA === "\"" && chB === "'") { + return 1; + } + if (chA === "'" && chB === "\"") { + return -1; + } + var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + if (cmp !== 0) { + return cmp; } } - function createChildItem(node) { - switch (node.kind) { - case 142: - if (ts.isBindingPattern(node.name)) { - break; - } - if ((node.flags & 1023) === 0) { - return undefined; - } - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147: - case 146: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 149: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 150: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 153: - return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 224: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); - case 255: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 225: - return createItem(node, getModuleName(node), ts.ScriptElementKind.moduleElement); - case 222: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); - case 223: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.typeElement); - case 151: - return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 152: - return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 145: - case 144: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 221: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.classElement); - case 220: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 218: - case 169: - var variableDeclarationNode = void 0; - var name_36; - if (node.kind === 169) { - name_36 = node.name; - variableDeclarationNode = node; - while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(variableDeclarationNode !== undefined); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_36 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.constElement); - } - else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.letElement); - } - else { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.variableElement); - } - case 148: - return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 238: - case 234: - case 229: - case 231: - case 232: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); - } - return undefined; - function createItem(node, name, scriptElementKind) { - return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]); - } + return a.length - b.length; + }; + function tryGetName(node) { + if (node.kind === 225) { + return getModuleName(node); } - function isEmpty(text) { - return !text || text.trim() === ""; + var decl = node; + if (decl.name) { + return ts.getPropertyNameForPropertyNameNode(decl.name); } - function getNavigationBarItem(text, kind, kindModifiers, spans, childItems, indent) { - if (childItems === void 0) { childItems = []; } - if (indent === void 0) { indent = 0; } - if (isEmpty(text)) { + switch (node.kind) { + case 179: + case 180: + case 192: + return getFunctionOrClassName(node); + case 279: + return getJSDocTypedefTagName(node); + default: return undefined; + } + } + function getItemName(node) { + if (node.kind === 225) { + return getModuleName(node); + } + var name = node.name; + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; } + } + switch (node.kind) { + case 256: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 180: + case 220: + case 179: + case 221: + case 192: + if (node.flags & 512) { + return "default"; + } + return getFunctionOrClassName(node); + case 148: + return "constructor"; + case 152: + return "new()"; + case 151: + return "()"; + case 153: + return "[]"; + case 279: + return getJSDocTypedefTagName(node); + default: + ts.Debug.fail(); + return ""; + } + } + function getJSDocTypedefTagName(node) { + if (node.name) { + return node.name.text; + } + else { + var parentNode = node.parent && node.parent.parent; + if (parentNode && parentNode.kind === 200) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (nameIdentifier.kind === 69) { + return nameIdentifier.text; + } + } + } + return ""; + } + } + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 221: + case 192: + case 224: + case 222: + case 225: + case 256: + case 223: + case 279: + return true; + case 148: + case 147: + case 149: + case 150: + return hasSomeImportantChild(item); + case 180: + case 220: + case 179: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 226: + case 256: + case 147: + case 148: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.forEach(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 218 && childKind !== 169; + }); + } + } + } + var emptyChildItemArray = []; + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { return { - text: text, - kind: kind, - kindModifiers: kindModifiers, - spans: spans, - childItems: childItems, - indent: indent, + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, bolded: false, grayed: false }; } - function createTopLevelItem(node) { - switch (node.kind) { - case 256: - return createSourceFileItem(node); - case 221: - return createClassItem(node); - case 147: - case 148: - return createMemberFunctionLikeItem(node); - case 224: - return createEnumItem(node); - case 222: - return createInterfaceItem(node); - case 225: - return createModuleItem(node); - case 220: - return createFunctionItem(node); - case 223: - return createTypeAliasItem(node); - } - return undefined; - function createModuleItem(node) { - var moduleName = getModuleName(node); - var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem); - return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createFunctionItem(node) { - if (node.body && node.body.kind === 199) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return undefined; } - function createTypeAliasItem(node) { - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.typeElement, ts.getNodeModifiers(node), [getNodeSpan(node)], [], getIndent(node)); - } - function createMemberFunctionLikeItem(node) { - if (node.body && node.body.kind === 199) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - var scriptElementKind = void 0; - var memberFunctionName = void 0; - if (node.kind === 147) { - memberFunctionName = ts.getPropertyNameForPropertyNameNode(node.name); - scriptElementKind = ts.ScriptElementKind.memberFunctionElement; - } - else { - memberFunctionName = "constructor"; - scriptElementKind = ts.ScriptElementKind.constructorImplementationElement; - } - return getNavigationBarItem(memberFunctionName, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - return undefined; - } - function createSourceFileItem(node) { - var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); - var rootName = ts.isExternalModule(node) - ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\"" - : ""; - return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems); - } - function createClassItem(node) { - var childItems; - if (node.members) { - var constructor = ts.forEach(node.members, function (member) { - return member.kind === 148 && member; - }); - var nodes = removeDynamicallyNamedProperties(node); - if (constructor) { - ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); })); - } - childItems = getItemsWorker(sortNodes(nodes), createChildItem); - } - var nodeName = !node.name ? "default" : node.name.text; - return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createEnumItem(node) { - var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createInterfaceItem(node) { - var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - } - function getModuleName(moduleDeclaration) { - if (ts.isAmbientModule(moduleDeclaration)) { - return getTextOfNode(moduleDeclaration.name); - } - var result = []; - result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { - moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); - } - return result.join("."); - } - function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 140; }); - } - function removeDynamicallyNamedProperties(node) { - return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); - } - function getInnermostModule(node) { - while (node.body.kind === 225) { - node = node.body; - } - return node; - } - function getNodeSpan(node) { - return node.kind === 256 - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getTextOfNode(node) { - return ts.getTextOfNodeFromSourceText(sourceFile.text, node); + return spans; } } - NavigationBar.getNavigationBarItems = getNavigationBarItems; - function getJsNavigationBarItems(sourceFile, compilerOptions) { - var anonFnText = ""; - var anonClassText = ""; - var indent = 0; - var rootName = ts.isExternalModule(sourceFile) ? - "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" - : ""; - var sourceFileItem = getNavBarItem(rootName, ts.ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]); - var topItem = sourceFileItem; - ts.forEachChild(sourceFile, visitNode); - function visitNode(node) { - var newItem = createNavBarItem(node); - if (newItem) { - topItem.childItems.push(newItem); - } - if (node.jsDocComments && node.jsDocComments.length > 0) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - visitNode(jsDocComment); - } - } - if (newItem && (ts.isFunctionLike(node) || ts.isClassLike(node))) { - var lastTop = topItem; - indent++; - topItem = newItem; - ts.forEachChild(node, visitNode); - topItem = lastTop; - indent--; - if (newItem && newItem.text === anonFnText && newItem.childItems.length === 0) { - topItem.childItems.pop(); - } - } - else { - ts.forEachChild(node, visitNode); - } - } - function createNavBarItem(node) { - switch (node.kind) { - case 218: - if (node.parent.parent - .parent.kind !== 256) { - return undefined; + function nodeKind(node) { + switch (node.kind) { + case 256: + return ts.ScriptElementKind.moduleElement; + case 255: + return ts.ScriptElementKind.memberVariableElement; + case 218: + case 169: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169) { + name_38 = node.name; + variableDeclarationNode = node; + while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { + variableDeclarationNode = variableDeclarationNode.parent; } - var varDecl = node; - if (varDecl.initializer && (varDecl.initializer.kind === 179 || - varDecl.initializer.kind === 180 || - varDecl.initializer.kind === 192)) { - return undefined; - } - case 220: - case 221: - case 148: - case 149: - case 150: - var name_37 = node.flags && (node.flags & 512) && !node.name ? "default" : - node.kind === 148 ? "constructor" : - ts.declarationNameToString(node.name); - return getNavBarItem(name_37, getScriptKindForElementKind(node.kind), [getNodeSpan(node)]); - case 179: - case 180: - case 192: - return getDefineModuleItem(node) || getFunctionOrClassExpressionItem(node); - case 147: - var methodDecl = node; - return getNavBarItem(ts.declarationNameToString(methodDecl.name), ts.ScriptElementKind.memberFunctionElement, [getNodeSpan(node)]); - case 235: - return getNavBarItem("default", ts.ScriptElementKind.variableElement, [getNodeSpan(node)]); - case 231: - if (!node.name) { - return undefined; - } - case 234: - case 232: - case 238: - if (node.kind === 238) { - if (!node.parent.parent.moduleSpecifier && !node.propertyName) { - return undefined; - } - } - var decl = node; - if (!decl.name) { - return undefined; - } - var declName = ts.declarationNameToString(decl.name); - return getNavBarItem(declName, ts.ScriptElementKind.constElement, [getNodeSpan(node)]); - case 279: - if (node.name) { - return getNavBarItem(node.name.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69) { - return getNavBarItem(nameIdentifier.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - } - } - } - default: - return undefined; - } - } - function getNavBarItem(text, kind, spans, kindModifiers) { - if (kindModifiers === void 0) { kindModifiers = ts.ScriptElementKindModifier.none; } - return { - text: text, kind: kind, kindModifiers: kindModifiers, spans: spans, childItems: [], indent: indent, bolded: false, grayed: false - }; - } - function getDefineModuleItem(node) { - if (node.kind !== 179 && node.kind !== 180) { - return undefined; - } - if (node.parent.kind !== 174) { - return undefined; - } - var callExpr = node.parent; - if (callExpr.expression.kind !== 69 || callExpr.expression.getText() !== "define") { - return undefined; - } - var defaultName = node.getSourceFile().fileName; - if (callExpr.arguments[0].kind === 9) { - defaultName = (callExpr.arguments[0]).text; - } - return getNavBarItem(defaultName, ts.ScriptElementKind.moduleElement, [getNodeSpan(node.parent)]); - } - function getFunctionOrClassExpressionItem(node) { - if (node.kind !== 179 && - node.kind !== 180 && - node.kind !== 192) { - return undefined; - } - var fnExpr = node; - var fnName; - if (fnExpr.name && ts.getFullWidth(fnExpr.name) > 0) { - fnName = ts.declarationNameToString(fnExpr.name); - } - else { - if (fnExpr.parent.kind === 218) { - fnName = ts.declarationNameToString(fnExpr.parent.name); - } - else if (fnExpr.parent.kind === 187 && - fnExpr.parent.operatorToken.kind === 56) { - fnName = fnExpr.parent.left.getText(); - } - else if (fnExpr.parent.kind === 253 && - fnExpr.parent.name) { - fnName = fnExpr.parent.name.getText(); + ts.Debug.assert(!!variableDeclarationNode); } else { - fnName = node.kind === 192 ? anonClassText : anonFnText; + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; } - } - var scriptKind = node.kind === 192 ? ts.ScriptElementKind.classElement : ts.ScriptElementKind.functionElement; - return getNavBarItem(fnName, scriptKind, [getNodeSpan(node)]); - } - function getNodeSpan(node) { - return node.kind === 256 - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getScriptKindForElementKind(kind) { - switch (kind) { - case 218: + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { return ts.ScriptElementKind.variableElement; - case 220: - return ts.ScriptElementKind.functionElement; - case 221: - return ts.ScriptElementKind.classElement; - case 148: - return ts.ScriptElementKind.constructorImplementationElement; - case 149: - return ts.ScriptElementKind.memberGetAccessorElement; - case 150: - return ts.ScriptElementKind.memberSetAccessorElement; - default: - return "unknown"; - } + } + case 180: + return ts.ScriptElementKind.functionElement; + case 279: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); } - return sourceFileItem.childItems; } - NavigationBar.getJsNavigationBarItems = getJsNavigationBarItems; + function getModuleName(moduleDeclaration) { + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + var result = []; + result.push(moduleDeclaration.name.text); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { + moduleDeclaration = moduleDeclaration.body; + result.push(moduleDeclaration.name.text); + } + return result.join("."); + } + function getInteriorModule(decl) { + return decl.body.kind === 225 ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 140; + } + function getNodeSpan(node) { + return node.kind === 256 + ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) + : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); + } + function getFunctionOrClassName(node) { + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + else if (node.parent.kind === 218) { + return ts.declarationNameToString(node.parent.name); + } + else if (node.parent.kind === 187 && + node.parent.operatorToken.kind === 56) { + return nodeText(node.parent.left); + } + else if (node.parent.kind === 253 && node.parent.name) { + return nodeText(node.parent.name); + } + else if (node.flags & 512) { + return "default"; + } + else { + return ts.isClassLike(node) ? "" : ""; + } + } + function isFunctionOrClassExpression(node) { + return node.kind === 179 || node.kind === 180 || node.kind === 192; + } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); var ts; @@ -40372,9 +40989,9 @@ var ts; getTypingNamesFromNodeModuleFolder(nodeModulesPath); } getTypingNamesFromSourceFileNames(fileNames); - for (var name_38 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_38) && !inferredTypings[name_38]) { - inferredTypings[name_38] = packageNameToTypingLocation[name_38]; + for (var name_39 in packageNameToTypingLocation) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { @@ -40442,9 +41059,9 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, "*.json", undefined, 2); - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); if (ts.getBaseFileName(normalizedFileName) !== "package.json") { continue; @@ -41032,9 +41649,9 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_39 in o) { - if (o[name_39] === rule) { - return name_39; + for (var name_40 in o) { + if (o[name_40] === rule) { + return name_40; } } throw new Error("Unknown rule"); @@ -42880,8 +43497,8 @@ var ts; var list = createNode(282, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -43007,7 +43624,7 @@ var ts; } addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); } - if (declaration.kind === 225 && declaration.body.kind === 225) { + if (declaration.kind === 225 && declaration.body && declaration.body.kind === 225) { return; } if ((declaration.kind === 179 || declaration.kind === 180) && @@ -43706,9 +44323,9 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptions_stringToEnum; + var commandLineOptionsStringToEnum; function fixupCompilerOptions(options, diagnostics) { - commandLineOptions_stringToEnum = commandLineOptions_stringToEnum || ts.filter(ts.optionDeclarations, function (o) { + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); @@ -43726,8 +44343,8 @@ var ts; } } }; - for (var _i = 0, commandLineOptions_stringToEnum_1 = commandLineOptions_stringToEnum; _i < commandLineOptions_stringToEnum_1.length; _i++) { - var opt = commandLineOptions_stringToEnum_1[_i]; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; _loop_2(opt); } return options; @@ -43739,6 +44356,16 @@ var ts; options.suppressOutputPathCheck = true; options.allowNonTsExtensions = true; options.noLib = true; + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; options.noResolve = true; var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); var sourceFile = ts.createSourceFile(inputFileName, input, options.target); @@ -43768,7 +44395,8 @@ var ts; getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; } + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -43837,7 +44465,7 @@ var ts; var buckets = {}; var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + settings.typesRoot + "|" + settings.typesSearchPaths + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); + return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = ts.lookUp(buckets, key); @@ -44487,7 +45115,8 @@ var ts; oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs); + oldSettings.allowJs !== newSettings.allowJs || + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); var compilerHost = { getSourceFile: getOrCreateSourceFile, getSourceFileByPath: getOrCreateSourceFileByPath, @@ -44507,8 +45136,10 @@ var ts; return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); }, directoryExists: function (directoryName) { - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; } }; if (host.trace) { @@ -45164,8 +45795,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_40 = element.propertyName || element.name; - existingImportsOrExports[name_40.text] = true; + var name_41 = element.propertyName || element.name; + existingImportsOrExports[name_41.text] = true; } if (ts.isEmpty(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -45260,13 +45891,13 @@ var ts; var entries = []; var target = program.getCompilerOptions().target; var nameTable = getNameTable(sourceFile); - for (var name_41 in nameTable) { - if (nameTable[name_41] === position) { + for (var name_42 in nameTable) { + if (nameTable[name_42] === position) { continue; } - if (!uniqueNames[name_41]) { - uniqueNames[name_41] = name_41; - var displayName = getCompletionEntryDisplayName(name_41, target, true); + if (!uniqueNames[name_42]) { + uniqueNames[name_42] = name_42; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, true); if (displayName) { var entry = { name: displayName, @@ -45370,10 +46001,10 @@ var ts; var typeChecker = program.getTypeChecker(); var type = typeChecker.getContextualType(node); if (type) { - var entries_1 = []; - addStringLiteralCompletionsFromType(type, entries_1); - if (entries_1.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_1 }; + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -46572,7 +47203,8 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference + isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isDefinition: false }); } } @@ -46853,7 +47485,8 @@ var ts; references: [{ fileName: sourceFile.fileName, textSpan: ts.createTextSpan(position, searchText.length), - isWriteAccess: false + isWriteAccess: false, + isDefinition: false }] }); } @@ -47231,7 +47864,8 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node) + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) }; } function isWriteAccess(node) { @@ -47452,7 +48086,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); + return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -47831,7 +48465,8 @@ var ts; return; case 142: if (token.parent.name === token) { - return 17; + var isThis = token.kind === 69 && token.originalKeywordKind === 97; + return isThis ? 3 : 17; } return; } @@ -49028,7 +49663,7 @@ var ts; Session.prototype.getDefinition = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49046,7 +49681,7 @@ var ts; Session.prototype.getTypeDefinition = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49064,7 +49699,7 @@ var ts; Session.prototype.getOccurrences = function (line, offset, fileName) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49088,7 +49723,7 @@ var ts; Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49115,8 +49750,12 @@ var ts; Session.prototype.getProjectInfo = function (fileName, needFileNameList) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); + if (!project) { + throw Errors.NoProject; + } var projectInfo = { - configFileName: project.projectFilename + configFileName: project.projectFilename, + languageServiceDisabled: project.languageServiceDiabled }; if (needFileNameList) { projectInfo.fileNames = project.getFileNames(); @@ -49127,10 +49766,11 @@ var ts; var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - if (!projects.length) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var defaultProject = projects[0]; + var defaultProject = projectsWithLanguageServiceEnabeld[0]; var defaultProjectCompilerService = defaultProject.compilerService; var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); @@ -49143,7 +49783,7 @@ var ts; locs: [] }; } - var fileSpans = server.combineProjectOutput(projects, function (project) { + var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); if (!renameLocations) { @@ -49195,10 +49835,11 @@ var ts; var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - if (!projects.length) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var defaultProject = projects[0]; + var defaultProject = projectsWithLanguageServiceEnabeld[0]; var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); if (!nameInfo) { @@ -49208,7 +49849,7 @@ var ts; var nameSpan = nameInfo.textSpan; var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset; var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projects, function (project) { + var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var references = compilerService.languageService.getReferencesAtPosition(file, position); if (!references) { @@ -49224,7 +49865,8 @@ var ts; start: start, lineText: lineText, end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition }; }); }, compareFileStart, areReferencesResponseItemsForTheSameLocation); @@ -49253,7 +49895,7 @@ var ts; Session.prototype.getQuickInfo = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49276,7 +49918,7 @@ var ts; Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49297,7 +49939,7 @@ var ts; Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49360,7 +50002,7 @@ var ts; } var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49379,7 +50021,7 @@ var ts; Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49395,7 +50037,7 @@ var ts; Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49422,7 +50064,7 @@ var ts; var checkList = fileNames.reduce(function (accum, fileName) { fileName = ts.normalizePath(fileName); var project = _this.projectService.getProjectForFile(fileName); - if (project) { + if (project && !project.languageServiceDiabled) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -49435,7 +50077,7 @@ var ts; var _this = this; var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { var compilerService = project.compilerService; var start = compilerService.host.lineOffsetToPosition(file, line, offset); var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); @@ -49452,7 +50094,7 @@ var ts; var file = ts.normalizePath(fileName); var tmpfile = ts.normalizePath(tempFileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { this.changeSeq++; project.compilerService.host.reloadScript(file, tmpfile, function () { _this.output(undefined, CommandNames.Reload, reqSeq); @@ -49463,7 +50105,7 @@ var ts; var file = ts.normalizePath(fileName); var tmpfile = ts.normalizePath(tempFileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { project.compilerService.host.saveTo(file, tmpfile); } }; @@ -49474,7 +50116,7 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items) { + Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { var _this = this; if (!items) { return undefined; @@ -49485,17 +50127,17 @@ var ts; kind: item.kind, kindModifiers: item.kindModifiers, spans: item.spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(fileName, span.start), - end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span)) + start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), + end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems), + childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), indent: item.indent }); }); }; Session.prototype.getNavigationBarItems = function (fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49503,17 +50145,17 @@ var ts; if (!items) { return undefined; } - return this.decorateNavigationBarItem(project, fileName, items); + return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); }; Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount) { var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - var defaultProject = projects[0]; - if (!defaultProject) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var allNavToItems = server.combineProjectOutput(projects, function (project) { + var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount); if (!navItems) { @@ -49557,7 +50199,7 @@ var ts; Session.prototype.getBraceMatching = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49573,7 +50215,10 @@ var ts; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var fileNames = this.getProjectInfo(fileName, true).fileNames; + var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + if (languageServiceDisabled) { + return; + } var fileNamesInProject = fileNames.filter(function (value, index, array) { return value.indexOf("lib.d.ts") < 0; }); var highPriorityFiles = []; var mediumPriorityFiles = []; @@ -49683,6 +50328,7 @@ var ts; } }); } + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; var ScriptInfo = (function () { function ScriptInfo(host, fileName, content, isOpen) { if (isOpen === void 0) { isOpen = false; } @@ -49752,17 +50398,17 @@ var ts; var resolvedModules = []; var compilerOptions = this.getCompilationSettings(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_42 = names_2[_i]; - var resolution = ts.lookUp(newResolutions, name_42); + var name_43 = names_2[_i]; + var resolution = ts.lookUp(newResolutions, name_43); if (!resolution) { - var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_42); + var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_43); if (moduleResolutionIsValid(existingResolution)) { resolution = existingResolution; } else { - resolution = loader(name_42, containingFile, compilerOptions, this.moduleResolutionHost); + resolution = loader(name_43, containingFile, compilerOptions, this.moduleResolutionHost); resolution.lastCheckTime = Date.now(); - newResolutions[name_42] = resolution; + newResolutions[name_43] = resolution; } } ts.Debug.assert(resolution !== undefined); @@ -49898,6 +50544,9 @@ var ts; LSHost.prototype.directoryExists = function (path) { return this.host.directoryExists(path); }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; LSHost.prototype.lineToTextSpan = function (filename, line) { var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); var script = this.filenameToScript.get(path); @@ -49920,20 +50569,25 @@ var ts; var lineInfo = index.lineNumberToInfo(line); return (lineInfo.offset + offset - 1); }; - LSHost.prototype.positionToLineOffset = function (filename, position) { + LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) { + lineIndex = lineIndex || this.getLineIndex(filename); + var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + LSHost.prototype.getLineIndex = function (filename) { var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + return script.snap().index; }; return LSHost; }()); server.LSHost = LSHost; var Project = (function () { - function Project(projectService, projectOptions) { + function Project(projectService, projectOptions, languageServiceDiabled) { + if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } this.projectService = projectService; this.projectOptions = projectOptions; + this.languageServiceDiabled = languageServiceDiabled; this.directoriesWatchedForTsconfig = []; this.filenameToSourceFile = {}; this.updateGraphSeq = 0; @@ -49941,8 +50595,19 @@ var ts; if (projectOptions && projectOptions.files) { projectOptions.compilerOptions.allowNonTsExtensions = true; } - this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); + if (!languageServiceDiabled) { + this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); + } } + Project.prototype.enableLanguageService = function () { + if (this.languageServiceDiabled) { + this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions); + } + this.languageServiceDiabled = false; + }; + Project.prototype.disableLanguageService = function () { + this.languageServiceDiabled = true; + }; Project.prototype.addOpenRef = function () { this.openRefCount++; }; @@ -49954,16 +50619,36 @@ var ts; return this.projectService.openFile(filename, false); }; Project.prototype.getRootFiles = function () { + if (this.languageServiceDiabled) { + return this.projectOptions ? this.projectOptions.files : undefined; + } return this.compilerService.host.roots.map(function (info) { return info.fileName; }); }; Project.prototype.getFileNames = function () { + if (this.languageServiceDiabled) { + if (!this.projectOptions) { + return undefined; + } + var fileNames = []; + if (this.projectOptions && this.projectOptions.compilerOptions) { + fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions)); + } + ts.addRange(fileNames, this.projectOptions.files); + return fileNames; + } var sourceFiles = this.program.getSourceFiles(); return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; }); }; Project.prototype.getSourceFile = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } return this.filenameToSourceFile[info.fileName]; }; Project.prototype.getSourceFileFromName = function (filename, requireOpen) { + if (this.languageServiceDiabled) { + return undefined; + } var info = this.projectService.getScriptInfo(filename); if (info) { if ((!requireOpen) || info.isOpen) { @@ -49972,13 +50657,22 @@ var ts; } }; Project.prototype.isRoot = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } return this.compilerService.host.roots.some(function (root) { return root === info; }); }; Project.prototype.removeReferencedFile = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.removeReferencedFile(info); this.updateGraph(); }; Project.prototype.updateFileMap = function () { + if (this.languageServiceDiabled) { + return; + } this.filenameToSourceFile = {}; var sourceFiles = this.program.getSourceFiles(); for (var i = 0, len = sourceFiles.length; i < len; i++) { @@ -49987,10 +50681,16 @@ var ts; } }; Project.prototype.finishGraph = function () { + if (this.languageServiceDiabled) { + return; + } this.updateGraph(); this.compilerService.languageService.getNavigateToItems(".*"); }; Project.prototype.updateGraph = function () { + if (this.languageServiceDiabled) { + return; + } this.program = this.compilerService.languageService.getProgram(); this.updateFileMap(); }; @@ -49998,12 +50698,25 @@ var ts; return this.projectFilename; }; Project.prototype.addRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.addRoot(info); }; Project.prototype.removeRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.removeRoot(info); }; Project.prototype.filesToString = function () { + if (this.languageServiceDiabled) { + if (this.projectOptions) { + var strBuilder_1 = ""; + ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; }); + return strBuilder_1; + } + } var strBuilder = ""; ts.forEachValue(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); return strBuilder; @@ -50012,7 +50725,9 @@ var ts; this.projectOptions = projectOptions; if (projectOptions.compilerOptions) { projectOptions.compilerOptions.allowNonTsExtensions = true; - this.compilerService.setCompilerOptions(projectOptions.compilerOptions); + if (!this.languageServiceDiabled) { + this.compilerService.setCompilerOptions(projectOptions.compilerOptions); + } } }; return Project; @@ -50222,6 +50937,8 @@ var ts; if (project.isConfiguredProject()) { project.projectFileWatcher.close(); project.directoryWatcher.close(); + ts.forEachValue(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); + delete project.directoriesWatchedForWildcards; this.configuredProjects = copyListRemovingItem(project, this.configuredProjects); } else { @@ -50237,8 +50954,8 @@ var ts; this.inferredProjects = copyListRemovingItem(project, this.inferredProjects); } var fileNames = project.getFileNames(); - for (var _b = 0, fileNames_2 = fileNames; _b < fileNames_2.length; _b++) { - var fileName = fileNames_2[_b]; + for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { + var fileName = fileNames_3[_b]; var info = this.getScriptInfo(fileName); if (info.defaultProject == project) { info.defaultProject = undefined; @@ -50263,6 +50980,7 @@ var ts; else { this.findReferencingProjects(info); if (info.defaultProject) { + info.defaultProject.addOpenRef(); this.openFilesReferenced.push(info); } else { @@ -50615,12 +51333,30 @@ var ts; else { var projectOptions = { files: parsedCommandLine.fileNames, + wildcardDirectories: parsedCommandLine.wildcardDirectories, compilerOptions: parsedCommandLine.options }; return { succeeded: true, projectOptions: projectOptions }; } } }; + ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { + var totalNonTsFileSize = 0; + if (!this.host.getFileSize) { + return false; + } + for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) { + var fileName = fileNames_4[_i]; + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { var _this = this; var _a = this.configFileToProjectOptions(configFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; @@ -50628,23 +51364,39 @@ var ts; return { success: false, errors: errors }; } else { - var project_1 = this.createProject(configFilename, projectOptions); + if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { + if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + var project_1 = this.createProject(configFilename, projectOptions, true); + project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); + return { success: true, project: project_1 }; + } + } + var project_2 = this.createProject(configFilename, projectOptions); var errors_1; for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { var rootFilename = _b[_i]; if (this.host.fileExists(rootFilename)) { var info = this.openFile(rootFilename, clientFileName == rootFilename); - project_1.addRoot(info); + project_2.addRoot(info); } else { (errors_1 || (errors_1 = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); } } - project_1.finishGraph(); - project_1.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); - this.log("Add recursive watcher for: " + ts.getDirectoryPath(configFilename)); - project_1.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(configFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project_1, path); }, true); - return { success: true, project: project_1, errors: errors_1 }; + project_2.finishGraph(); + project_2.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_2); }); + var configDirectoryPath_1 = ts.getDirectoryPath(configFilename); + this.log("Add recursive watcher for: " + configDirectoryPath_1); + project_2.directoryWatcher = this.host.watchDirectory(configDirectoryPath_1, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, true); + project_2.directoriesWatchedForWildcards = ts.reduceProperties(projectOptions.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath_1, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, recursive); + } + return watchers; + }, {}); + return { success: true, project: project_2, errors: errors_1 }; } }; ProjectService.prototype.updateConfiguredProject = function (project) { @@ -50659,19 +51411,45 @@ var ts; return errors; } else { - var oldFileNames_1 = project.compilerService.host.roots.map(function (info) { return info.fileName; }); + if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + project.setProjectOptions(projectOptions); + if (project.languageServiceDiabled) { + return; + } + project.disableLanguageService(); + if (project.directoryWatcher) { + project.directoryWatcher.close(); + project.directoryWatcher = undefined; + } + return; + } + if (project.languageServiceDiabled) { + project.setProjectOptions(projectOptions); + project.enableLanguageService(); + project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); + for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { + var rootFilename = _b[_i]; + if (this.host.fileExists(rootFilename)) { + var info = this.openFile(rootFilename, false); + project.addRoot(info); + } + } + project.finishGraph(); + return; + } + var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; }); var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; }); - for (var _i = 0, fileNamesToRemove_1 = fileNamesToRemove; _i < fileNamesToRemove_1.length; _i++) { - var fileName = fileNamesToRemove_1[_i]; + for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) { + var fileName = fileNamesToRemove_1[_c]; var info = this.getScriptInfo(fileName); if (info) { project.removeRoot(info); } } - for (var _b = 0, fileNamesToAdd_1 = fileNamesToAdd; _b < fileNamesToAdd_1.length; _b++) { - var fileName = fileNamesToAdd_1[_b]; + for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) { + var fileName = fileNamesToAdd_1[_d]; var info = this.getScriptInfo(fileName); if (!info) { info = this.openFile(fileName, false); @@ -50698,8 +51476,8 @@ var ts; } } }; - ProjectService.prototype.createProject = function (projectFilename, projectOptions) { - var project = new Project(this, projectOptions); + ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { + var project = new Project(this, projectOptions, languageServiceDisabled); project.projectFilename = projectFilename; return project; }; @@ -51986,6 +52764,7 @@ var ts; function CoreServicesShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } @@ -51993,15 +52772,24 @@ var ts; this.realpath = function (path) { return _this.shimHost.realpath(path); }; } } - CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude, depth) { - var encoded; + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude), depth); + var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); } catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); + var results = []; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { + var file = _b[_a]; + if (!ts.contains(results, file)) { + results.push(file); + } + } + } + return results; } - return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -52009,6 +52797,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; + CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { + return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index e8eae372528..aef7909bd45 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -704,7 +704,6 @@ declare namespace ts { } interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; - dotToken: Node; name: Identifier; } type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression; @@ -835,6 +834,7 @@ declare namespace ts { interface SwitchStatement extends Statement { expression: Expression; caseBlock: CaseBlock; + possiblyExhaustive?: boolean; } interface CaseBlock extends Node { clauses: NodeArray; @@ -910,7 +910,7 @@ declare namespace ts { type ModuleBody = ModuleBlock | ModuleDeclaration; interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; - body: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | ModuleDeclaration; } interface ModuleBlock extends Node, Statement { statements: NodeArray; @@ -1066,8 +1066,9 @@ declare namespace ts { Assignment = 16, TrueCondition = 32, FalseCondition = 64, - Referenced = 128, - Shared = 256, + SwitchClause = 128, + Referenced = 256, + Shared = 512, Label = 12, Condition = 96, } @@ -1089,6 +1090,12 @@ declare namespace ts { expression: Expression; antecedent: FlowNode; } + interface FlowSwitchClause extends FlowNode { + switchStatement: SwitchStatement; + clauseStart: number; + clauseEnd: number; + antecedent: FlowNode; + } interface AmdDependency { path: string; name: string; @@ -1132,7 +1139,9 @@ declare namespace ts { getCurrentDirectory(): string; } interface ParseConfigHost { - readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; + useCaseSensitiveFileNames: boolean; + readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[]; + fileExists(path: string): boolean; } interface WriteFileCallback { (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; @@ -1504,6 +1513,7 @@ declare namespace ts { resolvedJsxType?: Type; hasSuperCall?: boolean; superCall?: ExpressionStatement; + switchTypes?: Type[]; } const enum TypeFlags { Any = 1, @@ -1535,7 +1545,7 @@ declare namespace ts { ObjectLiteralPatternWithComputedProperties = 67108864, Never = 134217728, Nullable = 96, - Falsy = 126, + Falsy = 112, Intrinsic = 150995071, Primitive = 16777726, StringLike = 258, @@ -1772,8 +1782,9 @@ declare namespace ts { suppressOutputPathCheck?: boolean; target?: ScriptTarget; traceResolution?: boolean; + disableSizeLimit?: boolean; types?: string[]; - typesRoot?: string; + typeRoots?: string[]; typesSearchPaths?: string[]; version?: boolean; watch?: boolean; @@ -1843,6 +1854,15 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; + wildcardDirectories?: Map; + } + const enum WatchDirectoryFlags { + None = 0, + Recursive = 1, + } + interface ExpandResult { + fileNames: string[]; + wildcardDirectories: Map; } interface CommandLineOptionBase { name: string; @@ -2027,6 +2047,7 @@ declare namespace ts { getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; + getDirectories(path: string): string[]; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; @@ -2068,8 +2089,10 @@ declare namespace ts { function forEach(array: T[], callback: (element: T, index: number) => U): U; function contains(array: T[], value: T, areEqual?: (a: T, b: T) => boolean): boolean; function indexOf(array: T[], value: T): number; + function indexOfAnyCharCode(text: string, charCodes: number[], start?: number): number; function countWhere(array: T[], predicate: (x: T) => boolean): number; function filter(array: T[], f: (x: T) => boolean): T[]; + function filterMutate(array: T[], f: (x: T) => boolean): void; function map(array: T[], f: (x: T) => U): U[]; function concatenate(array1: T[], array2: T[]): T[]; function deduplicate(array: T[], areEqual?: (a: T, b: T) => boolean): T[]; @@ -2104,6 +2127,8 @@ declare namespace ts { function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage, ...args: any[]): DiagnosticMessageChain; function concatenateDiagnosticMessageChains(headChain: DiagnosticMessageChain, tailChain: DiagnosticMessageChain): DiagnosticMessageChain; function compareValues(a: T, b: T): Comparison; + function compareStrings(a: string, b: string, ignoreCase?: boolean): Comparison; + function compareStringsCaseInsensitive(a: string, b: string): Comparison; function compareDiagnostics(d1: Diagnostic, d2: Diagnostic): Comparison; function sortAndDeduplicateDiagnostics(diagnostics: Diagnostic[]): Diagnostic[]; function deduplicateSortedDiagnostics(diagnostics: Diagnostic[]): Diagnostic[]; @@ -2121,16 +2146,45 @@ declare namespace ts { function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: (fileName: string) => string, isAbsolutePathAnUrl: boolean): string; function getBaseFileName(path: string): string; function combinePaths(path1: string, path2: string): string; + function removeTrailingDirectorySeparator(path: string): string; + function ensureTrailingDirectorySeparator(path: string): string; + function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison; + function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean; function fileExtensionIs(path: string, extension: string): boolean; + function fileExtensionIsAny(path: string, extensions: string[]): boolean; + function getRegularExpressionForWildcard(specs: string[], basePath: string, usage: "files" | "directories" | "exclude"): string; + interface FileSystemEntries { + files: string[]; + directories: string[]; + } + interface FileMatcherPatterns { + includeFilePattern: string; + includeDirectoryPattern: string; + excludePattern: string; + basePaths: string[]; + } + function getFileMatcherPatterns(path: string, extensions: string[], excludes: string[], includes: string[], useCaseSensitiveFileNames: boolean, currentDirectory: string): FileMatcherPatterns; + function matchFiles(path: string, extensions: string[], excludes: string[], includes: string[], useCaseSensitiveFileNames: boolean, currentDirectory: string, getFileSystemEntries: (path: string) => FileSystemEntries): string[]; function ensureScriptKind(fileName: string, scriptKind?: ScriptKind): ScriptKind; function getScriptKindFromFileName(fileName: string): ScriptKind; const supportedTypeScriptExtensions: string[]; const supportedJavascriptExtensions: string[]; function getSupportedExtensions(options?: CompilerOptions): string[]; function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions): boolean; + const enum ExtensionPriority { + TypeScriptFiles = 0, + DeclarationAndJavaScriptFiles = 2, + Limit = 5, + Highest = 0, + Lowest = 2, + } + function getExtensionPriority(path: string, supportedExtensions: string[]): ExtensionPriority; + function adjustExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority; + function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority; function removeFileExtension(path: string): string; function tryRemoveExtension(path: string, extension: string): string; function isJsxOrTsxExtension(ext: string): boolean; + function changeExtension(path: T, newExtension: string): T; interface ObjectAllocator { getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node; getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile; @@ -2167,6 +2221,7 @@ declare namespace ts { useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string; + getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; @@ -2177,7 +2232,7 @@ declare namespace ts { getExecutingFilePath(): string; getCurrentDirectory(): string; getDirectories(path: string): string[]; - readDirectory(path: string, extension?: string, exclude?: string[]): string[]; + readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; getModifiedTime?(path: string): Date; createHash?(data: string): string; getMemoryUsage?(): number; @@ -3053,7 +3108,7 @@ declare namespace ts { key: string; message: string; }; - A_parameter_property_may_not_be_a_binding_pattern: { + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: number; category: DiagnosticCategory; key: string; @@ -3149,12 +3204,6 @@ declare namespace ts { key: string; message: string; }; - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; Decorators_are_not_valid_here: { code: number; category: DiagnosticCategory; @@ -3479,6 +3528,12 @@ declare namespace ts { key: string; message: string; }; + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Duplicate_identifier_0: { code: number; category: DiagnosticCategory; @@ -5099,6 +5154,18 @@ declare namespace ts { key: string; message: string; }; + Cannot_find_type_definition_file_for_0: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Cannot_extend_an_interface_0_Did_you_mean_implements: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Import_declaration_0_is_using_private_name_1: { code: number; category: DiagnosticCategory; @@ -5537,6 +5604,18 @@ declare namespace ts { key: string; message: string; }; + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Cannot_read_file_0_Colon_1: { code: number; category: DiagnosticCategory; @@ -6575,12 +6654,6 @@ declare namespace ts { key: string; message: string; }; - property_declarations_can_only_be_used_in_a_ts_file: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; enum_declarations_can_only_be_used_in_a_ts_file: { code: number; category: DiagnosticCategory; @@ -6742,7 +6815,7 @@ declare namespace ts { function getOptionNameMap(): OptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic; function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]): number | string; - function parseListTypeOption(opt: CommandLineOptionOfListType, value: string, errors: Diagnostic[]): (string | number)[]; + function parseListTypeOption(opt: CommandLineOptionOfListType, value: string, errors: Diagnostic[]): (string | number)[] | undefined; function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; function readConfigFile(fileName: string, readFile: (path: string) => string): { config?: any; @@ -6818,6 +6891,7 @@ declare namespace ts { function makeIdentifierFromModuleName(moduleName: string): string; function isBlockOrCatchScoped(declaration: Declaration): boolean; function isAmbientModule(node: Node): boolean; + function isShorthandAmbientModule(node: Node): boolean; function isBlockScopedContainerTopLevel(node: Node): boolean; function isGlobalScopeAugmentation(module: ModuleDeclaration): boolean; function isExternalModuleAugmentation(node: Node): boolean; @@ -6880,6 +6954,7 @@ declare namespace ts { function isInJavaScriptFile(node: Node): boolean; function isRequireCall(expression: Node, checkArgumentIsStringLiteral: boolean): expression is CallExpression; function isSingleOrDoubleQuote(charCode: number): boolean; + function isDeclarationOfFunctionExpression(s: Symbol): boolean; function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind; function getExternalModuleName(node: Node): Expression; function hasQuestionToken(node: Node): boolean; @@ -6994,6 +7069,7 @@ declare namespace ts { function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean; function getLocalSymbolForExportDefault(symbol: Symbol): Symbol; function hasJavaScriptFileExtension(fileName: string): boolean; + function hasTypeScriptFileExtension(fileName: string): boolean; const stringify: (value: any) => string; function convertToBase64(input: string): string; function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string; @@ -7105,7 +7181,7 @@ declare namespace ts { function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function getDefaultTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; + function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts.BreakpointResolver { @@ -7118,8 +7194,7 @@ declare namespace ts.NavigateTo { function getNavigateToItems(program: Program, checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[]; } declare namespace ts.NavigationBar { - function getNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): ts.NavigationBarItem[]; - function getJsNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): NavigationBarItem[]; + function getNavigationBarItems(sourceFile: SourceFile): NavigationBarItem[]; } declare namespace ts { enum PatternMatchKind { @@ -7229,7 +7304,7 @@ declare namespace ts.JsTyping { directoryExists: (path: string) => boolean; fileExists: (fileName: string) => boolean; readFile: (path: string, encoding?: string) => string; - readDirectory: (path: string, extension?: string, exclude?: string[], depth?: number) => string[]; + readDirectory: (rootDir: string, extensions: string[], excludes: string[], includes: string[], depth?: number) => string[]; } function discoverTypings(host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, typingOptions: TypingOptions, compilerOptions: CompilerOptions): { cachedTypingPaths: string[]; @@ -7716,6 +7791,7 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; + getDirectories?(directoryName: string): string[]; } interface LanguageService { cleanupSemanticCache(): void; @@ -7799,6 +7875,7 @@ declare namespace ts { textSpan: TextSpan; fileName: string; isWriteAccess: boolean; + isDefinition: boolean; } interface DocumentHighlights { fileName: string; @@ -8216,7 +8293,7 @@ declare namespace ts.server { private reload(fileName, tempFileName, reqSeq?); private saveToTmp(fileName, tempFileName); private closeClientFile(fileName); - private decorateNavigationBarItem(project, fileName, items); + private decorateNavigationBarItem(project, fileName, items, lineIndex); private getNavigationBarItems(fileName); private getNavigateToItems(searchValue, fileName, maxResultCount?); private getBraceMatching(line, offset, fileName); @@ -8246,6 +8323,7 @@ declare namespace ts.server { endGroup(): void; msg(s: string, type?: string): void; } + const maxProgramSizeForNonTsFiles: number; class ScriptInfo { private host; fileName: string; @@ -8304,27 +8382,34 @@ declare namespace ts.server { resolvePath(path: string): string; fileExists(path: string): boolean; directoryExists(path: string): boolean; + getDirectories(path: string): string[]; lineToTextSpan(filename: string, line: number): ts.TextSpan; lineOffsetToPosition(filename: string, line: number, offset: number): number; - positionToLineOffset(filename: string, position: number): ILineInfo; + positionToLineOffset(filename: string, position: number, lineIndex?: LineIndex): ILineInfo; + getLineIndex(filename: string): LineIndex; } interface ProjectOptions { files?: string[]; + wildcardDirectories?: ts.Map; compilerOptions?: ts.CompilerOptions; } class Project { projectService: ProjectService; projectOptions?: ProjectOptions; + languageServiceDiabled: boolean; compilerService: CompilerService; projectFilename: string; projectFileWatcher: FileWatcher; directoryWatcher: FileWatcher; + directoriesWatchedForWildcards: Map; directoriesWatchedForTsconfig: string[]; program: ts.Program; filenameToSourceFile: ts.Map; updateGraphSeq: number; openRefCount: number; - constructor(projectService: ProjectService, projectOptions?: ProjectOptions); + constructor(projectService: ProjectService, projectOptions?: ProjectOptions, languageServiceDiabled?: boolean); + enableLanguageService(): void; + disableLanguageService(): void; addOpenRef(): void; deleteOpenRef(): number; openReferencedFile(filename: string): ScriptInfo; @@ -8415,13 +8500,14 @@ declare namespace ts.server { projectOptions?: ProjectOptions; errors?: Diagnostic[]; }; + private exceedTotalNonTsFileSizeLimit(fileNames); openConfigFile(configFilename: string, clientFileName?: string): { success: boolean; project?: Project; errors?: Diagnostic[]; }; updateConfiguredProject(project: Project): Diagnostic[]; - createProject(projectFilename: string, projectOptions?: ProjectOptions): Project; + createProject(projectFilename: string, projectOptions?: ProjectOptions, languageServiceDisabled?: boolean): Project; } class CompilerService { project: Project; @@ -8592,7 +8678,9 @@ declare namespace ts { directoryExists(directoryName: string): boolean; } interface CoreServicesShimHost extends Logger, ModuleResolutionHost { - readDirectory(rootDir: string, extension: string, exclude?: string, depth?: number): string; + readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; + useCaseSensitiveFileNames?(): boolean; + getCurrentDirectory(): string; trace(s: string): void; } interface IFileReference { @@ -8685,10 +8773,12 @@ declare namespace ts { private shimHost; directoryExists: (directoryName: string) => boolean; realpath: (path: string) => string; + useCaseSensitiveFileNames: boolean; constructor(shimHost: CoreServicesShimHost); - readDirectory(rootDir: string, extension: string, exclude: string[], depth?: number): string[]; + readDirectory(rootDir: string, extensions: string[], exclude: string[], include: string[], depth?: number): string[]; fileExists(fileName: string): boolean; readFile(fileName: string): string; + private readDirectoryFallback(rootDir, extension, exclude); } function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { message: string; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 2da5d67be8a..22a420c25e4 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -147,6 +147,15 @@ var ts; return -1; } ts.indexOf = indexOf; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0, len = text.length; i < len; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; function countWhere(array, predicate) { var count = 0; if (array) { @@ -174,12 +183,24 @@ var ts; return result; } ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + if (f(item)) { + array[outIndex] = item; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; function map(array, f) { var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result.push(f(v)); } } @@ -198,8 +219,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; if (!contains(result, item, areEqual)) { result.push(item); } @@ -210,8 +231,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var v = array_7[_i]; result += v[prop]; } return result; @@ -505,6 +526,30 @@ var ts; return a < b ? -1 : 1; } ts.compareValues = compareValues; + function compareStrings(a, b, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + if (ignoreCase) { + if (String.prototype.localeCompare) { + var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); + return result < 0 ? -1 : result > 0 ? 1 : 0; + } + a = a.toUpperCase(); + b = b.toUpperCase(); + if (a === b) + return 0; + } + return a < b ? -1 : 1; + } + ts.compareStrings = compareStrings; + function compareStringsCaseInsensitive(a, b) { + return compareStrings(a, b, true); + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } @@ -727,12 +772,220 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; + function removeTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) === ts.directorySeparator) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) !== ts.directorySeparator) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + a = removeTrailingDirectorySeparator(a); + b = removeTrailingDirectorySeparator(b); + var aComponents = getNormalizedPathComponents(a, currentDirectory); + var bComponents = getNormalizedPathComponents(b, currentDirectory); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + if (result !== 0) { + return result; + } + } + return compareValues(aComponents.length, bComponents.length); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + parent = removeTrailingDirectorySeparator(parent); + child = removeTrailingDirectorySeparator(child); + if (parent === child) + return true; + var parentComponents = getNormalizedPathComponents(parent, currentDirectory); + var childComponents = getNormalizedPathComponents(child, currentDirectory); + if (childComponents.length < parentComponents.length) { + return false; + } + for (var i = 0; i < parentComponents.length; i++) { + var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); + if (result !== 0) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; function fileExtensionIs(path, extension) { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsAny(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsAny = fileExtensionIsAny; + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42, 63]; + function getRegularExpressionForWildcard(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + var pattern = ""; + var hasWrittenSubpattern = false; + spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + var spec = specs_1[_i]; + if (!spec) { + continue; + } + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + if (usage !== "exclude" && components[components.length - 1] === "**") { + continue spec; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + var optionalCount = 0; + for (var _a = 0, components_1 = components; _a < components_1.length; _a++) { + var component = components_1[_a]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + continue spec; + } + subpattern += "(/.+?)?"; + hasRecursiveDirectoryWildcard = true; + hasWrittenComponent = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + hasWrittenComponent = true; + } + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + if (hasWrittenSubpattern) { + pattern += "|"; + } + pattern += "(" + subpattern + ")"; + hasWrittenSubpattern = true; + } + if (!pattern) { + return undefined; + } + return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + } + function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var regexFlag = useCaseSensitiveFileNames ? "" : "i"; + var includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag); + var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); + var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var result = []; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + } + return result; + function visitDirectory(path, absolutePath) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; + var name_1 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!extensions || fileExtensionIsAny(name_1, extensions)) && + (!includeFileRegex || includeFileRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + result.push(name_1); + } + } + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var current = directories_1[_b]; + var name_2 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name_2, absoluteName); + } + } + } + } + ts.matchFiles = matchFiles; + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + var basePaths = [path]; + if (includes) { + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + if (isRootedDiskPath(include)) { + var wildcardOffset = indexOfAnyCharCode(include, wildcardCharCodes); + var includeBasePath = wildcardOffset < 0 + ? removeTrailingDirectorySeparator(getDirectoryPath(include)) + : include.substring(0, include.lastIndexOf(ts.directorySeparator, wildcardOffset)); + includeBasePaths.push(includeBasePath); + } + } + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + include: for (var i = 0; i < includeBasePaths.length; i++) { + var includeBasePath = includeBasePaths[i]; + for (var j = 0; j < basePaths.length; j++) { + if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { + continue include; + } + } + basePaths.push(includeBasePath); + } + } + return basePaths; + } function ensureScriptKind(fileName, scriptKind) { return (scriptKind || getScriptKindFromFileName(fileName)) || 3; } @@ -773,6 +1026,36 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i); + } + } + return 0; + } + ts.getExtensionPriority = getExtensionPriority; + function adjustExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 0; + } + else if (extensionPriority < 5) { + return 2; + } + else { + return 5; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + function getNextLowestExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 2; + } + else { + return 5; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { @@ -793,6 +1076,10 @@ var ts; return ext === ".jsx" || ext === ".tsx"; } ts.isJsxOrTsxExtension = isJsxOrTsxExtension; + function changeExtension(path, newExtension) { + return (removeFileExtension(path) + newExtension); + } + ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -863,6 +1150,7 @@ var ts; ts.sys = (function () { function getWScriptSystem() { var fso = new ActiveXObject("Scripting.FileSystemObject"); + var shell = new ActiveXObject("WScript.Shell"); var fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2; var binaryStream = new ActiveXObject("ADODB.Stream"); @@ -917,9 +1205,6 @@ var ts; fileStream.Close(); } } - function getCanonicalPath(path) { - return path.toLowerCase(); - } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -931,30 +1216,19 @@ var ts; var folder = fso.GetFolder(path); return getNames(folder.subfolders); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { + function getAccessibleFileSystemEntries(path) { + try { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; - var name_1 = ts.combinePaths(path, current); - if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { - result.push(name_1); - } - } - var subfolders = getNames(folder.subfolders); - for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { - var current = subfolders_1[_a]; - var name_2 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_2))) { - visitDirectory(name_2); - } - } + var directories = getNames(folder.subfolders); + return { files: files, directories: directories }; } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } return { args: args, @@ -983,7 +1257,7 @@ var ts; return WScript.ScriptFullName; }, getCurrentDirectory: function () { - return new ActiveXObject("WScript.Shell").CurrentDirectory; + return shell.CurrentDirectory; }, getDirectories: getDirectories, readDirectory: readDirectory, @@ -1112,8 +1386,39 @@ var ts; } } } - function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path : path.toLowerCase(); + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var entry = entries_1[_i]; + if (entry === "." || entry === "..") { + continue; + } + var name_3 = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name_3); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } function fileSystemEntryExists(path, entryKind) { try { @@ -1136,38 +1441,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { - var files = _fs.readdirSync(path || ".").sort(); - var directories = []; - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var current = files_2[_i]; - if (current === "." || current === "..") { - continue; - } - var name_3 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_3))) { - var stat = _fs.statSync(name_3); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name_3, extension)) { - result.push(name_3); - } - } - else if (stat.isDirectory()) { - directories.push(name_3); - } - } - } - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var current = directories_1[_a]; - visitDirectory(current); - } - } - } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -1249,6 +1522,16 @@ var ts; } return process.memoryUsage().heapUsed; }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (e) { } + return 0; + }, exit: function (exitCode) { process.exit(exitCode); }, @@ -1280,7 +1563,10 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - readDirectory: ChakraHost.readDirectory, + readDirectory: function (path, extensions, excludes, includes) { + var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, exit: ChakraHost.quit, realpath: realpath }; @@ -1445,7 +1731,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_a_binding_pattern_1187", message: "A parameter property may not be a binding pattern." }, + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, @@ -1461,7 +1747,6 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower_1204", message: "Cannot compile modules into 'es2015' when targeting 'ES5' or lower." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -1516,6 +1801,7 @@ var ts; Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -1786,6 +2072,8 @@ var ts; The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, + Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, + Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1859,6 +2147,8 @@ var ts; Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." }, Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, @@ -2032,7 +2322,6 @@ var ts; types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "property_declarations_can_only_be_used_in_a_ts_file_8014", message: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, @@ -3861,8 +4150,13 @@ var ts; } }, { - name: "typesRoot", - type: "string" + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + } }, { name: "types", @@ -3928,6 +4222,10 @@ var ts; }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, + { + name: "disableProjectSizeLimit", + type: "boolean" + }, { name: "strictNullChecks", type: "boolean", @@ -3993,7 +4291,15 @@ var ts; } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { - var values = trimString((value || "")).split(","); + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); switch (opt.element.type) { case "number": return ts.map(values, parseInt); @@ -4050,8 +4356,11 @@ var ts; i++; break; case "list": - options[opt.name] = parseListTypeOption(opt, args[i], errors); - i++; + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } break; default: options[opt.name] = parseCustomTypeOption(opt, args[i], errors); @@ -4143,7 +4452,7 @@ var ts; } return output; } - var IgnoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -4151,66 +4460,57 @@ var ts; var options = ts.extend(existingOptions, compilerOptions); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; - var fileNames = getFileNames(errors); + var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, - errors: errors + errors: errors, + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { - var fileNames = []; + var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { - fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = json["files"]; } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); } } - else { - var filesSeen = {}; - var exclude = []; - if (ts.isArray(json["exclude"])) { - exclude = json["exclude"]; + var includeSpecs; + if (ts.hasProperty(json, "include")) { + if (ts.isArray(json["include"])) { + includeSpecs = json["include"]; } else { - exclude = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - exclude.push(outDir); - } - exclude = ts.map(exclude, function (e) { return ts.getNormalizedAbsolutePath(e, basePath); }); - var supportedExtensions = ts.getSupportedExtensions(options); - ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); - for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; - var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); - for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { - var fileName = filesInDirWithExtension_1[_a]; - if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { - continue; - } - if (IgnoreFileNamePattern.test(fileName)) { - continue; - } - if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { - var baseName = fileName.substr(0, fileName.length - extension.length); - if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { - continue; - } - } - filesSeen[fileName] = true; - fileNames.push(fileName); - } + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); } } - if (ts.hasProperty(json, "excludes") && !ts.hasProperty(json, "exclude")) { + var excludeSpecs; + if (ts.hasProperty(json, "exclude")) { + if (ts.isArray(json["exclude"])) { + excludeSpecs = json["exclude"]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + } + } + else if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - return fileNames; + else { + excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + } + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } + if (fileNames === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; @@ -4292,6 +4592,139 @@ var ts; function trimString(s) { return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var literalFileMap = {}; + var wildcardFileMap = {}; + if (include) { + include = validateSpecs(include, errors, false); + } + if (exclude) { + exclude = validateSpecs(exclude, errors, true); + } + var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var supportedExtensions = ts.getSupportedExtensions(options); + if (fileNames) { + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var file = ts.combinePaths(basePath, fileName); + literalFileMap[keyMapper(file)] = file; + } + } + if (include && include.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + var file = _b[_a]; + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + if (ignoreFileNamePattern.test(file)) { + continue; + } + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + wildcardFileMap[key] = file; + } + } + } + var literalFiles = ts.reduceProperties(literalFileMap, addFileToOutput, []); + var wildcardFiles = ts.reduceProperties(wildcardFileMap, addFileToOutput, []); + wildcardFiles.sort(host.useCaseSensitiveFileNames ? ts.compareStrings : ts.compareStringsCaseInsensitive); + return { + fileNames: literalFiles.concat(wildcardFiles), + wildcardDirectories: wildcardDirectories + }; + } + function validateSpecs(specs, errors, allowTrailingRecursion) { + var validSpecs = []; + for (var _i = 0, specs_2 = specs; _i < specs_2.length; _i++) { + var spec = specs_2[_i]; + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + } + else { + validSpecs.push(spec); + } + } + return validSpecs; + } + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var name_5 = ts.combinePaths(path, file); + if (excludeRegex && excludeRegex.test(name_5)) { + continue; + } + var match = wildcardDirectoryPattern.exec(name_5); + if (match) { + var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); + var flags = watchRecursivePattern.test(name_5) ? 1 : 0; + var existingFlags = ts.getProperty(wildcardDirectories, key); + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1) { + recursiveKeys.push(key); + } + } + } + } + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + for (var i = 0; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + return true; + } + } + return false; + } + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + delete wildcardFiles[lowerPriorityPath]; + } + } + function addFileToOutput(output, file) { + output.push(file); + return output; + } + function caseSensitiveKeyMapper(key) { + return key; + } + function caseInsensitiveKeyMapper(key) { + return key.toLowerCase(); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -4572,6 +5005,10 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModule(node) { + return node.kind === 225 && (!node.body); + } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || @@ -4900,9 +5337,9 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_5 = node.name; - if (name_5 && name_5.kind === 140) { - traverse(name_5.expression); + var name_6 = node.name; + if (name_6 && name_6.kind === 140) { + traverse(name_6.expression); return; } } @@ -4959,6 +5396,7 @@ var ts; case 157: return true; } + return false; } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { @@ -5336,6 +5774,14 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isDeclarationOfFunctionExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 218) { + var declaration = s.valueDeclaration; + return declaration.initializer && declaration.initializer.kind === 179; + } + return false; + } + ts.isDeclarationOfFunctionExpression = isDeclarationOfFunctionExpression; function getSpecialPropertyAssignmentKind(expression) { if (!isInJavaScriptFile(expression)) { return 0; @@ -5483,8 +5929,8 @@ var ts; var tag = _b[_a]; if (tag.kind === 275) { var parameterTag = tag; - var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_6.text === parameterName) { + var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_7.text === parameterName) { return parameterTag; } } @@ -6227,7 +6673,9 @@ var ts; ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; @@ -6541,6 +6989,10 @@ var ts; return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -6924,7 +7376,6 @@ var ts; return visitNodes(cbNodes, node.properties); case 172: return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); case 173: return visitNode(cbNode, node.expression) || @@ -7675,6 +8126,7 @@ var ts; return token === 19 || token === 15 || token === 37 + || token === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunction() { @@ -9182,7 +9634,7 @@ var ts; } var node = createNode(172, expression.pos); node.expression = expression; - node.dotToken = parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } @@ -9370,7 +9822,6 @@ var ts; if (dotToken) { var propertyAccess = createNode(172, expression.pos); propertyAccess.expression = expression; - propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); continue; @@ -10414,8 +10865,8 @@ var ts; return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_7 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, undefined); + var name_8 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_8, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -10558,7 +11009,12 @@ var ts; else { node.name = parseLiteralNode(true); } - node.body = parseModuleBlock(); + if (token === 15) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { @@ -11302,8 +11758,8 @@ var ts; if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_8 = jsDocTypeReference.name; - if (name_8.text === "Object") { + var name_9 = jsDocTypeReference.name; + if (name_9.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -11386,13 +11842,13 @@ var ts; var typeParameters = []; typeParameters.pos = scanner.getStartPos(); while (true) { - var name_9 = parseJSDocIdentifierName(); - if (!name_9) { + var name_10 = parseJSDocIdentifierName(); + if (!name_10) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_9.pos); - typeParameter.name = name_9; + var typeParameter = createNode(141, name_10.pos); + typeParameter.name = name_10; finishNode(typeParameter); typeParameters.push(typeParameter); if (token === 24) { @@ -11494,8 +11950,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -11567,8 +12023,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -11748,7 +12204,8 @@ var ts; return state_1; } else if (node.kind === 225) { - return getModuleInstanceState(node.body); + var body = node.body; + return body ? getModuleInstanceState(body) : 1; } else { return 1; @@ -12117,11 +12574,6 @@ var ts; break; } } - function isNarrowableReference(expr) { - return expr.kind === 69 || - expr.kind === 97 || - expr.kind === 172 && isNarrowableReference(expr.expression); - } function isNarrowingExpression(expr) { switch (expr.kind) { case 69: @@ -12129,7 +12581,7 @@ var ts; case 172: return isNarrowableReference(expr); case 174: - return true; + return hasNarrowableArgument(expr); case 178: return isNarrowingExpression(expr.expression); case 187: @@ -12139,6 +12591,35 @@ var ts; } return false; } + function isNarrowableReference(expr) { + return expr.kind === 69 || + expr.kind === 97 || + expr.kind === 172 && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 172 && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -12147,20 +12628,34 @@ var ts; case 31: case 32: case 33: - if (isNarrowingExpression(expr.left) && (expr.right.kind === 93 || expr.right.kind === 69)) { - return true; - } - if (expr.left.kind === 182 && isNarrowingExpression(expr.left.expression) && expr.right.kind === 9) { - return true; - } - return false; + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91: - return isNarrowingExpression(expr.left); + return isNarrowableOperand(expr.left); case 24: return isNarrowingExpression(expr.right); } return false; } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 178: + return isNarrowableOperand(expr.expression); + case 187: + switch (expr.operatorToken.kind) { + case 56: + return isNarrowableOperand(expr.left); + case 24: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4, @@ -12174,7 +12669,7 @@ var ts; }; } function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 128 ? 256 : 128; + flow.flags |= flow.flags & 256 ? 512 : 256; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { @@ -12199,8 +12694,21 @@ var ts; setFlowNodeReferenced(antecedent); return { flags: flags, - antecedent: antecedent, - expression: expression + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingSwitchStatement(switchStatement)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { @@ -12410,9 +12918,10 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasNonEmptyDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 && c.statements.length; }); - if (!hasNonEmptyDefault) { - addAntecedent(postSwitchLabel, preSwitchCaseFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250; }); + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); } currentBreakTarget = saveBreakTarget; preSwitchCaseFlow = savePreSwitchCaseFlow; @@ -12420,25 +12929,22 @@ var ts; } function bindCaseBlock(node) { var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { - var clause = clauses[i]; - if (clause.statements.length) { - if (currentFlow.flags & 1) { - currentFlow = preSwitchCaseFlow; - } - else { - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, preSwitchCaseFlow); - addAntecedent(preCaseLabel, currentFlow); - currentFlow = finishFlowLabel(preCaseLabel); - } - bind(clause); - if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; } - else { - bind(clause); + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } } @@ -12703,7 +13209,7 @@ var ts; } function hasExportDeclarations(node) { var body = node.kind === 256 ? node : node.body; - if (body.kind === 256 || body.kind === 226) { + if (body && (body.kind === 256 || body.kind === 226)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; if (stat.kind === 236 || stat.kind === 235) { @@ -13223,7 +13729,7 @@ var ts; constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; var funcSymbol = container.locals[constructorFunction.text]; - if (!funcSymbol || !(funcSymbol.flags & 16)) { + if (!funcSymbol || !(funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return; } if (!funcSymbol.members) { @@ -13808,7 +14314,8 @@ var ts; var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if (modulekind || (!compilerOptions.outFile && !compilerOptions.out)) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out)) { return true; } var sourceFiles = host.getSourceFiles(); @@ -14005,7 +14512,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -14061,6 +14569,29 @@ var ts; } return false; } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 || kind === 172) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64, true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); @@ -14103,9 +14634,11 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = moduleSymbol.exports["export="] ? - getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : - resolveSymbol(moduleSymbol.exports["default"]); + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + moduleSymbol : + moduleSymbol.exports["export="] ? + getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : + resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -14154,22 +14687,25 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_10 = specifier.propertyName || specifier.name; - if (name_10.text) { + var name_11 = specifier.propertyName || specifier.name; + if (name_11.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + return moduleSymbol; + } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_10.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_11.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_10.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_11.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_10, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_10)); + error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_11)); } return symbol; } @@ -15504,6 +16040,9 @@ var ts; function isTypeAny(type) { return type && (type.flags & 1) !== 0; } + function isTypeNever(type) { + return type && (type.flags & 134217728) !== 0; + } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); @@ -15539,19 +16078,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_11 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_11)) { + var name_12 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_12)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_11); + var text = getTextOfPropertyName(name_12); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_11, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_11)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_12)); return unknownType; } } @@ -15755,18 +16294,21 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } - if (declaration.kind === 187) { - return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - if (declaration.kind === 172) { - if (declaration.parent.kind === 187) { - return links.type = checkExpressionCached(declaration.parent.right); - } - } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + var type = undefined; + if (declaration.kind === 187) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + else if (declaration.kind === 172) { + if (declaration.parent.kind === 187) { + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + } if (!popTypeResolution()) { if (symbol.valueDeclaration.type) { type = unknownType; @@ -15854,9 +16396,14 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var type = createObjectType(65536, symbol); - links.type = strictNullChecks && symbol.flags & 536870912 ? - addTypeKind(type, 32) : type; + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + links.type = anyType; + } + else { + var type = createObjectType(65536, symbol); + links.type = strictNullChecks && symbol.flags & 536870912 ? + addTypeKind(type, 32) : type; + } } return links.type; } @@ -16807,7 +17354,7 @@ var ts; } return result; } - function isOptionalParameter(node) { + function isJSDocOptionalParameter(node) { if (node.flags & 134217728) { if (node.type && node.type.kind === 268) { return true; @@ -16822,7 +17369,9 @@ var ts; } } } - if (ts.hasQuestionToken(node)) { + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -16877,7 +17426,7 @@ var ts; if (param.type && param.type.kind === 166) { hasStringLiterals = true; } - if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { minArgumentCount = i - (hasThisParameter ? 1 : 0); } @@ -17874,6 +18423,9 @@ var ts; function isTypeComparableTo(source, target) { return checkTypeComparableTo(source, target, undefined); } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } @@ -18812,8 +19364,10 @@ var ts; function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralType(type) { - return type.flags & 256; + function isStringLiteralUnionType(type) { + return type.flags & 256 ? true : + type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } function isTupleType(type) { return !!(type.flags & 8192); @@ -19543,6 +20097,29 @@ var ts; } return node; } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 249) { + var expr = clause.expression; + return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + } + return undefined; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function filterType(type, f) { + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { @@ -19558,7 +20135,7 @@ var ts; return result; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 256) { + if (flow.flags & 512) { for (var i = visitedFlowStart; i < visitedFlowCount; i++) { if (visitedFlowNodes[i] === flow) { return visitedFlowTypes[i]; @@ -19576,6 +20153,9 @@ var ts; else if (flow.flags & 96) { type = getTypeAtFlowCondition(flow); } + else if (flow.flags & 128) { + type = getTypeAtSwitchClause(flow); + } else if (flow.flags & 12) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; @@ -19596,7 +20176,7 @@ var ts; else { type = declaredType; } - if (flow.flags & 256) { + if (flow.flags & 512) { visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; visitedFlowCount++; @@ -19634,6 +20214,10 @@ var ts; } return type; } + function getTypeAtSwitchClause(flow) { + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { @@ -19694,11 +20278,26 @@ var ts; case 31: case 32: case 33: - if (isNullOrUndefinedLiteral(expr.right)) { - return narrowTypeByNullCheck(type, expr, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (expr.left.kind === 182 && expr.right.kind === 9) { - return narrowTypeByTypeof(type, expr, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + } + if (left.kind === 182 && right.kind === 9) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + } + if (right.kind === 182 && left.kind === 9) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + } + if (left.kind === 172) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + } + if (right.kind === 172) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91: @@ -19708,46 +20307,91 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, expr, assumeTrue) { - var operator = expr.operatorToken.kind; + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(expr.left))) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } var doubleEquals = operator === 30 || operator === 31; var facts = doubleEquals ? assumeTrue ? 65536 : 524288 : - expr.right.kind === 93 ? + literal.kind === 93 ? assumeTrue ? 32768 : 262144 : assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - function narrowTypeByTypeof(type, expr, assumeTrue) { - var left = getReferenceFromExpression(expr.left.expression); - var right = expr.right; - if (!isMatchingReference(reference, left)) { - if (containsMatchingReference(reference, left)) { + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + var target = getReferenceFromExpression(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (expr.operatorToken.kind === 31 || - expr.operatorToken.kind === 33) { + if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } if (assumeTrue && !(type.flags & 16384)) { - var targetType = ts.getProperty(typeofTypesByName, right.text); + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, right.text) || 64 : - ts.getProperty(typeofNEFacts, right.text) || 8192; + ts.getProperty(typeofEQFacts, literal.text) || 64 : + ts.getProperty(typeofNEFacts, literal.text) || 8192; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 || operator === 33) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { @@ -20316,11 +20960,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_12 = declaration.propertyName || declaration.name; + var name_13 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_12)) { - var text = getTextOfPropertyName(name_12); + !ts.isBindingPattern(name_13)) { + var text = getTextOfPropertyName(name_13); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -20446,9 +21090,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } - function contextualTypeIsStringLiteralType(type) { - return !!(type.flags & 16384 ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); - } function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } @@ -21215,7 +21856,7 @@ var ts; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { - if (right.text) { + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); } return unknownType; @@ -21308,15 +21949,15 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_13 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_13 !== undefined) { - var prop = getPropertyOfType(objectType, name_13); + var name_14 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_14 !== undefined) { + var prop = getPropertyOfType(objectType, name_14); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_13, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_14, symbolToString(objectType.symbol)); return unknownType; } } @@ -22135,8 +22776,10 @@ var ts; declaration.kind !== 152 && declaration.kind !== 157 && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = checkExpression(node.expression).symbol; - if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16)) { + var funcSymbol = node.expression.kind === 69 ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return getInferredClassType(funcSymbol); } else if (compilerOptions.noImplicitAny) { @@ -22155,6 +22798,7 @@ var ts; } function checkAssertion(node) { var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); @@ -22238,6 +22882,14 @@ var ts; } return emptyObjectType; } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { @@ -22267,18 +22919,10 @@ var ts; else { types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { - return neverType; + return isAsync ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - if (isAsync) { - var promiseType = createPromiseType(voidType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - return voidType; + return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); @@ -22289,7 +22933,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -22300,17 +22944,7 @@ var ts; reportErrorsFromWidening(func, type); } var widenedType = getWidenedType(type); - if (isAsync) { - var promiseType = createPromiseType(widenedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - else { - return widenedType; - } + return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; @@ -22328,10 +22962,40 @@ var ts; }); return aggregatedTypes; } + function isExhaustiveSwitchStatement(node) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172) { + return false; + } + var type = checkExpression(expr.expression); + if (!(type.flags & 16384)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(propType, switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 32768)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 213 && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasReturnWithNoExpression = !!(func.flags & 32768); + var hasReturnWithNoExpression = functionHasImplicitReturn(func); var hasReturnOfTypeNever = false; ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; @@ -22369,7 +23033,7 @@ var ts; if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !(func.flags & 32768)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 65536; @@ -22662,14 +23326,14 @@ var ts; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_14 = property.name; - if (name_14.kind === 140) { - checkComputedPropertyName(name_14); + var name_15 = property.name; + if (name_15.kind === 140) { + checkComputedPropertyName(name_15); } - if (isComputedNonLiteralName(name_14)) { + if (isComputedNonLiteralName(name_15)) { return undefined; } - var text = getTextOfPropertyName(name_14); + var text = getTextOfPropertyName(name_15); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -22684,7 +23348,7 @@ var ts; } } else { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_14)); + error(name_15, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_15)); } } else { @@ -22880,7 +23544,7 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 126) : rightType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; case 52: return getUnionType([getNonNullableType(leftType), rightType]); case 56: @@ -22980,7 +23644,7 @@ var ts; } function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + if (contextualType && isStringLiteralUnionType(contextualType)) { return getStringLiteralTypeForText(node.text); } return stringType; @@ -23223,9 +23887,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_15 = _a[_i].name; - if (ts.isBindingPattern(name_15) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_15, parameterName, typePredicate.parameterName)) { + var name_16 = _a[_i].name; + if (ts.isBindingPattern(name_16) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -23253,15 +23917,15 @@ var ts; } function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var name_16 = _a[_i].name; - if (name_16.kind === 69 && - name_16.text === predicateVariableName) { + var name_17 = _a[_i].name; + if (name_17.kind === 69 && + name_17.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_16.kind === 168 || - name_16.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, predicateVariableNode, predicateVariableName)) { + else if (name_17.kind === 168 || + name_17.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_17, predicateVariableNode, predicateVariableName)) { return true; } } @@ -23729,7 +24393,6 @@ var ts; } } } - var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { @@ -23754,7 +24417,7 @@ var ts; duplicateFunctionDeclaration = true; } } - else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } if (ts.nodeIsPresent(node.body)) { @@ -23781,7 +24444,7 @@ var ts; error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); }); } - if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !(lastSeenNonAmbientDeclaration.flags & 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -23872,7 +24535,7 @@ var ts; } function checkNonThenableType(type, location, message) { type = getWidenedType(type); - if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) { if (location) { if (!message) { message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; @@ -23884,37 +24547,39 @@ var ts; return type; } function getPromisedType(promise) { - if (promise.flags & 1) { + if (isTypeAny(promise)) { return undefined; } - if ((promise.flags & 4096) && promise.target === tryGetGlobalPromiseType()) { - return promise.typeArguments[0]; + if (promise.flags & 4096) { + if (promise.target === tryGetGlobalPromiseType() + || promise.target === getGlobalPromiseLikeType()) { + return promise.typeArguments[0]; + } } var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (thenFunction && (thenFunction.flags & 1)) { + if (!thenFunction || isTypeAny(thenFunction)) { return undefined; } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : emptyArray; + var thenSignatures = getSignaturesOfType(thenFunction, 0); if (thenSignatures.length === 0) { return undefined; } var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); - if (onfulfilledParameterType.flags & 1) { + if (isTypeAny(onfulfilledParameterType)) { return undefined; } var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); - return valueParameterType; + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { - return getTypeAtPosition(signature, 0); + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; } function getAwaitedType(type) { return checkAwaitedType(type, undefined, undefined); @@ -24255,8 +24920,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_17 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_17, name_17); + var name_18 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_18, name_18); } } } @@ -24326,8 +24991,8 @@ var ts; } var parent_11 = node.parent.parent; var parentType = getTypeForBindingElementParent(parent_11); - var name_18 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_18)); + var name_19 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_19)); if (parent_11.initializer && property && getParentOfSymbol(property)) { checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); } @@ -25456,7 +26121,7 @@ var ts; if (isAmbientExternalModule) { if (ts.isExternalModuleAugmentation(node)) { var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); - if (checkBody) { + if (checkBody && node.body) { for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; checkModuleAugmentationElement(statement, isGlobalAugmentation); @@ -25481,7 +26146,12 @@ var ts; } } } - checkSourceElement(node.body); + if (compilerOptions.noImplicitAny && !node.body) { + reportImplicitAnyError(node, anyType); + } + if (node.body) { + checkSourceElement(node.body); + } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { @@ -25501,9 +26171,9 @@ var ts; break; case 169: case 218: - var name_19 = node.name; - if (ts.isBindingPattern(name_19)) { - for (var _b = 0, _c = name_19.elements; _b < _c.length; _b++) { + var name_20 = node.name; + if (ts.isBindingPattern(name_20)) { + for (var _b = 0, _c = name_20.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -26338,9 +27008,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_20 = symbol.name; + var name_21 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_20); + var symbol = getPropertyOfType(t, name_21); if (symbol) { symbols_3.push(symbol); } @@ -27041,7 +27711,10 @@ var ts; return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 142 && (flags & 92) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 142 && (flags & 92) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { return checkGrammarAsyncModifier(node, lastAsync); @@ -27285,10 +27958,10 @@ var ts; var SetAccessor = 4; var GetOrSetAccessor = GetAccessor | SetAccessor; var _loop_1 = function(prop) { - var name_21 = prop.name; + var name_22 = prop.name; if (prop.kind === 193 || - name_21.kind === 140) { - checkGrammarComputedPropertyName(name_21); + name_22.kind === 140) { + checkGrammarComputedPropertyName(name_22); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; @@ -27301,8 +27974,8 @@ var ts; var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_21.kind === 8) { - checkGrammarNumericLiteral(name_21); + if (name_22.kind === 8) { + checkGrammarNumericLiteral(name_22); } currentKind = Property; } @@ -27318,7 +27991,7 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_21); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_22); if (effectiveName === undefined) { return "continue"; } @@ -27328,18 +28001,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_21, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_21)); + grammarErrorOnNode(name_22, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_22)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } }; @@ -27357,12 +28030,12 @@ var ts; continue; } var jsxAttr = attr; - var name_22 = jsxAttr.name; - if (!ts.hasProperty(seen, name_22.text)) { - seen[name_22.text] = true; + var name_23 = jsxAttr.name; + if (!ts.hasProperty(seen, name_23.text)) { + seen[name_23.text] = true; } else { - return grammarErrorOnNode(name_22, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_23, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -28425,9 +29098,9 @@ var ts; var count = 0; while (true) { count++; - var name_23 = baseName + "_" + count; - if (!ts.hasProperty(currentIdentifiers, name_23)) { - return name_23; + var name_24 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_24)) { + return name_24; } } } @@ -28695,21 +29368,26 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body.kind !== 226) { + while (node.body && node.body.kind !== 226) { node = node.body; write("."); writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; + if (node.body) { + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + else { + write(";"); + } } function writeTypeAliasDeclaration(node) { var prevEnclosingDeclaration = enclosingDeclaration; @@ -29909,19 +30587,19 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_24 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_24)) { + var name_25 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_25)) { tempFlags |= flags; - return name_24; + return name_25; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_25 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_25)) { - return name_25; + var name_26 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_26)) { + return name_26; } } } @@ -30617,8 +31295,8 @@ var ts; } else if (declaration.kind === 234) { write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_26 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_26); + var name_27 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_27); if (languageVersion === 0 && identifier === "default") { write('["default"]'); } @@ -30671,8 +31349,8 @@ var ts; function emitIdentifier(node) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_27 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_27); + var name_28 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_28); return; } } @@ -31010,7 +31688,6 @@ var ts; function createPropertyAccessExpression(expression, name) { var result = ts.createSynthesizedNode(172); result.expression = parenthesizeForAccess(expression); - result.dotToken = ts.createSynthesizedNode(21); result.name = name; return result; } @@ -31056,9 +31733,9 @@ var ts; emitTrailingCommentsOfPosition(node.initializer.pos); emit(node.initializer); } - function isNamespaceExportReference(node) { + function isExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 256; + return !!container; } function isImportedReference(node) { var declaration = resolver.getReferencedImportDeclaration(node); @@ -31066,9 +31743,9 @@ var ts; } function emitShorthandPropertyAssignment(node) { writeTextOfNode(currentText, node.name); - if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isNamespaceExportReference(node.name)) { + if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { write(": "); - emit(node.name); + emitExpressionIdentifier(node.name); } if (languageVersion >= 2 && node.objectAssignmentInitializer) { write(" = "); @@ -31117,13 +31794,16 @@ var ts; if (languageVersion === 2 && node.expression.kind === 95 && isInAsyncMethodWithSuperInES6(node)) { - var name_28 = ts.createSynthesizedNode(9); - name_28.text = node.name.text; - emitSuperAccessInAsyncMethod(node.expression, name_28); + var name_29 = ts.createSynthesizedNode(9); + name_29.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_29); return; } emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; + var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; + var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); var shouldEmitSpace = false; if (!indentedBeforeDot) { if (node.expression.kind === 8) { @@ -31141,7 +31821,7 @@ var ts; else { write("."); } - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -31514,7 +32194,6 @@ var ts; synthesizedLHS = ts.createSynthesizedNode(172, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; - synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; write(", "); } @@ -32790,12 +33469,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_29 = createTempVariable(0); + var name_30 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_29); - emit(name_29); + tempParameters.push(name_30); + emit(name_30); } else { emit(node.name); @@ -33586,7 +34265,11 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { + var isES6ExportedClass = isES6ExportedDeclaration(node); if (node.kind === 221) { + if (isES6ExportedClass && !(node.flags & 512)) { + write("export "); + } if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -33650,9 +34333,15 @@ var ts; write(";"); } emitEnd(node); - if (node.kind === 221) { + if (node.kind === 221 && !isES6ExportedClass) { emitExportMemberAssignment(node); } + else if (isES6ExportedClass && (node.flags & 512)) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); @@ -33948,10 +34637,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 160) { + if (parameterType && parameterType.kind === 160) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType && parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -33968,9 +34657,15 @@ var ts; } } function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node) && node.type) { - emitSerializedTypeNode(node.type); - return; + if (node && ts.isFunctionLike(node)) { + if (node.type) { + emitSerializedTypeNode(node.type); + return; + } + else if (ts.isAsyncFunctionLike(node)) { + write("Promise"); + return; + } } write("void 0"); } @@ -34103,7 +34798,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225) { + if (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -34144,6 +34839,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); + ts.Debug.assert(node.body !== undefined); if (node.body.kind === 226) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; @@ -34523,8 +35219,8 @@ var ts; else { for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_30 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_30] || (exportSpecifiers[name_30] = [])).push(specifier); + var name_31 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_31] || (exportSpecifiers[name_31] = [])).push(specifier); } } break; @@ -34562,9 +35258,9 @@ var ts; } function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { if (emitRelativePathAsModuleName) { - var name_31 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_31) { - return "\"" + name_31 + "\""; + var name_32 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_32) { + return "\"" + name_32 + "\""; } } var moduleName = ts.getExternalModuleName(importNode); @@ -34710,11 +35406,11 @@ var ts; var seen = {}; for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_32 = local.kind === 69 + var name_33 = local.kind === 69 ? local : local.name; - if (name_32) { - var text = ts.unescapeIdentifier(name_32.text); + if (name_33) { + var text = ts.unescapeIdentifier(name_33.text); if (ts.hasProperty(seen, text)) { continue; } @@ -34793,15 +35489,15 @@ var ts; } if (node.kind === 218 || node.kind === 169) { if (shouldHoistVariable(node, false)) { - var name_33 = node.name; - if (name_33.kind === 69) { + var name_34 = node.name; + if (name_34.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_33); + hoistedVars.push(name_34); } else { - ts.forEachChild(name_33, visit); + ts.forEachChild(name_34, visit); } } return; @@ -35711,13 +36407,9 @@ var ts; ts.emitTime = 0; ts.ioReadTime = 0; ts.ioWriteTime = 0; - var emptyArray = []; - var defaultLibrarySearchPaths = [ - "types/", - "node_modules/", - "node_modules/@types/", - ]; ts.version = "1.9.0"; + var emptyArray = []; + var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { while (true) { var fileName = ts.combinePaths(searchPath, "tsconfig.json"); @@ -35845,6 +36537,10 @@ var ts; return undefined; } var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + return options.typeRoots || + ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(), d); }); + } function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { @@ -35853,35 +36549,34 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); + var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; - if (rootDir !== undefined) { - var effectivePrimarySearchPaths = options.typesSearchPaths || defaultLibrarySearchPaths; - for (var _i = 0, effectivePrimarySearchPaths_1 = effectivePrimarySearchPaths; _i < effectivePrimarySearchPaths_1.length; _i++) { - var searchPath = effectivePrimarySearchPaths_1[_i]; - var primaryPath = ts.combinePaths(rootDir, searchPath); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, primaryPath); - } - var candidate = ts.combinePaths(primaryPath, typeReferenceDirectiveName); + if (typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { @@ -35905,9 +36600,6 @@ var ts; if (containingFile) { initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); } - else { - initialLocationForSecondaryLookup = rootDir; - } if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); @@ -36400,25 +37092,12 @@ var ts; } } } - function getDefaultTypeDirectiveNames(rootPath) { - var localTypes = ts.combinePaths(rootPath, "types"); - var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); - var result = []; - if (ts.sys.directoryExists(localTypes)) { - result = result.concat(ts.sys.getDirectories(localTypes)); - } - if (ts.sys.directoryExists(npmTypes)) { - result = result.concat(ts.sys.getDirectories(npmTypes)); - } - return result; - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { - getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -36431,6 +37110,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; } @@ -36473,32 +37153,39 @@ var ts; var resolutions = []; var cache = {}; for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_34 = names_1[_i]; + var name_35 = names_1[_i]; var result = void 0; - if (ts.hasProperty(cache, name_34)) { - result = cache[name_34]; + if (ts.hasProperty(cache, name_35)) { + result = cache[name_35]; } else { - result = loader(name_34, containingFile); - cache[name_34] = result; + result = loader(name_35, containingFile); + cache[name_35] = result; } resolutions.push(result); } return resolutions; } - function getDefaultTypeDirectiveNames(options, rootFiles, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { if (options.types) { return options.types; } - if (host && host.getDefaultTypeDirectiveNames) { - var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - if (commonRoot) { - return host.getDefaultTypeDirectiveNames(commonRoot); + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + result = result.concat(host.getDirectories(root)); + } } } - return undefined; + return result; } - ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -36535,9 +37222,11 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, undefined); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); } @@ -36600,8 +37289,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = {}; - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var sourceFile = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -36620,10 +37309,9 @@ var ts; (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs) || (oldOptions.rootDir !== options.rootDir) || - (oldOptions.typesSearchPaths !== options.typesSearchPaths) || (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.typesRoot !== options.typesRoot) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; @@ -36915,8 +37603,20 @@ var ts; } break; case 145: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; + var propertyDeclaration = node; + if (propertyDeclaration.modifiers) { + for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 113) { + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + } + } + } + if (checkTypeAnnotation(node.type)) { + return true; + } + break; case 224: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; @@ -37048,9 +37748,12 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, true); + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, true); + } } } } @@ -37197,7 +37900,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_name_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); } if (saveResolution) { resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective; @@ -37362,9 +38065,6 @@ var ts; var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - if (options.module === ts.ModuleKind.ES6 && languageVersion < 2) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); - } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); @@ -38069,10 +38769,10 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_35 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_35); + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_35); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -38083,14 +38783,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_35); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_35, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -38220,622 +38920,539 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile, compilerOptions) { - if (ts.isSourceFileJavaScript(sourceFile)) { - return getJsNavigationBarItems(sourceFile, compilerOptions); + function getNavigationBarItems(sourceFile) { + curSourceFile = sourceFile; + var result = ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + var curSourceFile; + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); } - return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); - function getIndent(node) { - var indent = 1; - var current = node.parent; - while (current) { - switch (current.kind) { - case 225: - do { - current = current.parent; - } while (current.kind === 225); - case 221: - case 224: - case 222: - case 220: - indent++; + else { + parent.children = [child]; + } + } + var parentsStack = []; + var parent; + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + parentsStack.push(parent); + parent = navNode; + } + function endNode() { + if (parent.children) { + mergeChildren(parent.children); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + function addChildrenRecursively(node) { + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 148: + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } } - current = current.parent; - } - return indent; - } - function getChildNodes(nodes) { - var childNodes = []; - function visit(node) { - switch (node.kind) { - case 200: - ts.forEach(node.declarationList.declarations, visit); - break; - case 167: - case 168: - ts.forEach(node.elements, visit); - break; - case 236: - if (node.exportClause) { - ts.forEach(node.exportClause.elements, visit); + break; + case 147: + case 149: + case 150: + case 146: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 145: + case 144: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 231: + var importClause = node; + if (importClause.name) { + addLeafNode(importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 232) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); } - break; - case 230: - var importClause = node.importClause; - if (importClause) { - if (importClause.name) { - childNodes.push(importClause); - } - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232) { - childNodes.push(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, visit); - } - } - } - break; - case 169: - case 218: - if (ts.isBindingPattern(node.name)) { - visit(node.name); - break; - } - case 221: - case 224: - case 222: - case 225: - case 220: - case 229: - case 234: - case 238: - case 223: - childNodes.push(node); - break; + } } - } - ts.forEach(nodes, visit); - return sortNodes(childNodes); - } - function getTopLevelNodes(node) { - var topLevelNodes = []; - topLevelNodes.push(node); - addTopLevelNodes(node.statements, topLevelNodes); - return topLevelNodes; - } - function sortNodes(nodes) { - return nodes.slice(0).sort(function (n1, n2) { - if (n1.name && n2.name) { - return localeCompareFix(ts.getPropertyNameForPropertyNameNode(n1.name), ts.getPropertyNameForPropertyNameNode(n2.name)); + break; + case 169: + case 218: + var decl = node; + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } - else if (n1.name) { - return 1; - } - else if (n2.name) { - return -1; + else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { + addChildrenRecursively(decl.initializer); } else { - return n1.kind - n2.kind; + addNodeWithRecursiveChild(decl, decl.initializer); } - }); - function localeCompareFix(a, b) { - var cmp = a.toLowerCase().localeCompare(b.toLowerCase()); - if (cmp !== 0) - return cmp; - return a < b ? 1 : a > b ? -1 : 0; - } - } - function addTopLevelNodes(nodes, topLevelNodes) { - nodes = sortNodes(nodes); - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; - switch (node.kind) { - case 221: - topLevelNodes.push(node); - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 147 || member.kind === 148) { - if (member.body) { - if (hasNamedFunctionDeclarations(member.body.statements)) { - topLevelNodes.push(member); - } - addTopLevelNodes(member.body.statements, topLevelNodes); - } + break; + case 180: + case 220: + case 179: + addNodeWithRecursiveChild(node, node.body); + break; + case 224: + startNode(node); + for (var _d = 0, _e = node.members; _d < _e.length; _d++) { + var member = _e[_d]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 221: + case 192: + case 222: + startNode(node); + for (var _f = 0, _g = node.members; _f < _g.length; _f++) { + var member = _g[_f]; + addChildrenRecursively(member); + } + endNode(); + break; + case 225: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 238: + case 229: + case 153: + case 151: + case 152: + case 223: + addLeafNode(node); + break; + default: + if (node.jsDocComments) { + for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { + var jsDocComment = _j[_h]; + for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { + var tag = _l[_k]; + if (tag.kind === 279) { + addLeafNode(tag); } } - break; - case 224: - case 222: - case 223: - topLevelNodes.push(node); - break; - case 225: - var moduleDeclaration = node; - topLevelNodes.push(node); - addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); - break; - case 220: - var functionDeclaration = node; - if (isTopLevelFunctionDeclaration(functionDeclaration)) { - topLevelNodes.push(node); - addTopLevelNodes(functionDeclaration.body.statements, topLevelNodes); - } - break; + } } - } + ts.forEachChild(node, addChildrenRecursively); } - function hasNamedFunctionDeclarations(nodes) { - for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { - var s = nodes_5[_i]; - if (s.kind === 220 && !isEmpty(s.name.text)) { + } + function mergeChildren(children) { + var nameToItems = {}; + ts.filterMutate(children, function (child) { + var decl = child.node; + var name = decl.name && nodeText(decl.name); + if (!name) { + return true; + } + var itemsWithSameName = ts.getProperty(nameToItems, name); + if (!itemsWithSameName) { + nameToItems[name] = child; + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child)) { + return false; + } + nameToItems[name] = [itemWithSameName, child]; + return true; + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); return true; } + return false; } - return false; - } - function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 220) { - if (functionDeclaration.body && functionDeclaration.body.kind === 199) { - if (hasNamedFunctionDeclarations(functionDeclaration.body.statements)) { - return true; - } - if (!ts.isFunctionBlock(functionDeclaration.parent)) { - return true; - } - else { - var grandParentKind = functionDeclaration.parent.parent.kind; - if (grandParentKind === 147 || - grandParentKind === 148) { - return true; - } - } + }); + function shouldReallyMerge(a, b) { + return a.kind === b.kind && (a.kind !== 225 || areSameModule(a, b)); + function areSameModule(a, b) { + if (a.body.kind !== b.body.kind) { + return false; } - } - return false; - } - function getItemsWorker(nodes, createItem) { - var items = []; - var keyToItem = {}; - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var child = nodes_6[_i]; - var item = createItem(child); - if (item !== undefined) { - if (item.text.length > 0) { - var key = item.text + "-" + item.kind + "-" + item.indent; - var itemWithSameName = keyToItem[key]; - if (itemWithSameName) { - merge(itemWithSameName, item); - } - else { - keyToItem[key] = item; - items.push(item); - } - } + if (a.body.kind !== 225) { + return true; } + return areSameModule(a.body, b.body); } - return items; } function merge(target, source) { - ts.addRange(target.spans, source.spans); - if (source.childItems) { - if (!target.childItems) { - target.childItems = []; - } - outer: for (var _i = 0, _a = source.childItems; _i < _a.length; _i++) { - var sourceChild = _a[_i]; - for (var _b = 0, _c = target.childItems; _b < _c.length; _b++) { - var targetChild = _c[_b]; - if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) { - merge(targetChild, sourceChild); - continue outer; - } - } - target.childItems.push(sourceChild); - } + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); + } + var _a; + } + } + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); + if (name1 && name2) { + var cmp = localeCompareFix(name1, name2); + return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + else { + return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + } + var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + for (var i = 0; i < Math.min(a.length, b.length); i++) { + var chA = a.charAt(i), chB = b.charAt(i); + if (chA === "\"" && chB === "'") { + return 1; + } + if (chA === "'" && chB === "\"") { + return -1; + } + var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + if (cmp !== 0) { + return cmp; } } - function createChildItem(node) { - switch (node.kind) { - case 142: - if (ts.isBindingPattern(node.name)) { - break; - } - if ((node.flags & 1023) === 0) { - return undefined; - } - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147: - case 146: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 149: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 150: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 153: - return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 224: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); - case 255: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 225: - return createItem(node, getModuleName(node), ts.ScriptElementKind.moduleElement); - case 222: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); - case 223: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.typeElement); - case 151: - return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 152: - return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 145: - case 144: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 221: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.classElement); - case 220: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 218: - case 169: - var variableDeclarationNode = void 0; - var name_36; - if (node.kind === 169) { - name_36 = node.name; - variableDeclarationNode = node; - while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(variableDeclarationNode !== undefined); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_36 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.constElement); - } - else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.letElement); - } - else { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.variableElement); - } - case 148: - return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 238: - case 234: - case 229: - case 231: - case 232: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); - } - return undefined; - function createItem(node, name, scriptElementKind) { - return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]); - } + return a.length - b.length; + }; + function tryGetName(node) { + if (node.kind === 225) { + return getModuleName(node); } - function isEmpty(text) { - return !text || text.trim() === ""; + var decl = node; + if (decl.name) { + return ts.getPropertyNameForPropertyNameNode(decl.name); } - function getNavigationBarItem(text, kind, kindModifiers, spans, childItems, indent) { - if (childItems === void 0) { childItems = []; } - if (indent === void 0) { indent = 0; } - if (isEmpty(text)) { + switch (node.kind) { + case 179: + case 180: + case 192: + return getFunctionOrClassName(node); + case 279: + return getJSDocTypedefTagName(node); + default: return undefined; + } + } + function getItemName(node) { + if (node.kind === 225) { + return getModuleName(node); + } + var name = node.name; + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; } + } + switch (node.kind) { + case 256: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 180: + case 220: + case 179: + case 221: + case 192: + if (node.flags & 512) { + return "default"; + } + return getFunctionOrClassName(node); + case 148: + return "constructor"; + case 152: + return "new()"; + case 151: + return "()"; + case 153: + return "[]"; + case 279: + return getJSDocTypedefTagName(node); + default: + ts.Debug.fail(); + return ""; + } + } + function getJSDocTypedefTagName(node) { + if (node.name) { + return node.name.text; + } + else { + var parentNode = node.parent && node.parent.parent; + if (parentNode && parentNode.kind === 200) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (nameIdentifier.kind === 69) { + return nameIdentifier.text; + } + } + } + return ""; + } + } + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 221: + case 192: + case 224: + case 222: + case 225: + case 256: + case 223: + case 279: + return true; + case 148: + case 147: + case 149: + case 150: + return hasSomeImportantChild(item); + case 180: + case 220: + case 179: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 226: + case 256: + case 147: + case 148: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.forEach(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 218 && childKind !== 169; + }); + } + } + } + var emptyChildItemArray = []; + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { return { - text: text, - kind: kind, - kindModifiers: kindModifiers, - spans: spans, - childItems: childItems, - indent: indent, + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, bolded: false, grayed: false }; } - function createTopLevelItem(node) { - switch (node.kind) { - case 256: - return createSourceFileItem(node); - case 221: - return createClassItem(node); - case 147: - case 148: - return createMemberFunctionLikeItem(node); - case 224: - return createEnumItem(node); - case 222: - return createInterfaceItem(node); - case 225: - return createModuleItem(node); - case 220: - return createFunctionItem(node); - case 223: - return createTypeAliasItem(node); - } - return undefined; - function createModuleItem(node) { - var moduleName = getModuleName(node); - var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem); - return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createFunctionItem(node) { - if (node.body && node.body.kind === 199) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return undefined; } - function createTypeAliasItem(node) { - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.typeElement, ts.getNodeModifiers(node), [getNodeSpan(node)], [], getIndent(node)); - } - function createMemberFunctionLikeItem(node) { - if (node.body && node.body.kind === 199) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - var scriptElementKind = void 0; - var memberFunctionName = void 0; - if (node.kind === 147) { - memberFunctionName = ts.getPropertyNameForPropertyNameNode(node.name); - scriptElementKind = ts.ScriptElementKind.memberFunctionElement; - } - else { - memberFunctionName = "constructor"; - scriptElementKind = ts.ScriptElementKind.constructorImplementationElement; - } - return getNavigationBarItem(memberFunctionName, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - return undefined; - } - function createSourceFileItem(node) { - var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); - var rootName = ts.isExternalModule(node) - ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\"" - : ""; - return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems); - } - function createClassItem(node) { - var childItems; - if (node.members) { - var constructor = ts.forEach(node.members, function (member) { - return member.kind === 148 && member; - }); - var nodes = removeDynamicallyNamedProperties(node); - if (constructor) { - ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); })); - } - childItems = getItemsWorker(sortNodes(nodes), createChildItem); - } - var nodeName = !node.name ? "default" : node.name.text; - return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createEnumItem(node) { - var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createInterfaceItem(node) { - var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - } - function getModuleName(moduleDeclaration) { - if (ts.isAmbientModule(moduleDeclaration)) { - return getTextOfNode(moduleDeclaration.name); - } - var result = []; - result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { - moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); - } - return result.join("."); - } - function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 140; }); - } - function removeDynamicallyNamedProperties(node) { - return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); - } - function getInnermostModule(node) { - while (node.body.kind === 225) { - node = node.body; - } - return node; - } - function getNodeSpan(node) { - return node.kind === 256 - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getTextOfNode(node) { - return ts.getTextOfNodeFromSourceText(sourceFile.text, node); + return spans; } } - NavigationBar.getNavigationBarItems = getNavigationBarItems; - function getJsNavigationBarItems(sourceFile, compilerOptions) { - var anonFnText = ""; - var anonClassText = ""; - var indent = 0; - var rootName = ts.isExternalModule(sourceFile) ? - "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" - : ""; - var sourceFileItem = getNavBarItem(rootName, ts.ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]); - var topItem = sourceFileItem; - ts.forEachChild(sourceFile, visitNode); - function visitNode(node) { - var newItem = createNavBarItem(node); - if (newItem) { - topItem.childItems.push(newItem); - } - if (node.jsDocComments && node.jsDocComments.length > 0) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - visitNode(jsDocComment); - } - } - if (newItem && (ts.isFunctionLike(node) || ts.isClassLike(node))) { - var lastTop = topItem; - indent++; - topItem = newItem; - ts.forEachChild(node, visitNode); - topItem = lastTop; - indent--; - if (newItem && newItem.text === anonFnText && newItem.childItems.length === 0) { - topItem.childItems.pop(); - } - } - else { - ts.forEachChild(node, visitNode); - } - } - function createNavBarItem(node) { - switch (node.kind) { - case 218: - if (node.parent.parent - .parent.kind !== 256) { - return undefined; + function nodeKind(node) { + switch (node.kind) { + case 256: + return ts.ScriptElementKind.moduleElement; + case 255: + return ts.ScriptElementKind.memberVariableElement; + case 218: + case 169: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169) { + name_38 = node.name; + variableDeclarationNode = node; + while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { + variableDeclarationNode = variableDeclarationNode.parent; } - var varDecl = node; - if (varDecl.initializer && (varDecl.initializer.kind === 179 || - varDecl.initializer.kind === 180 || - varDecl.initializer.kind === 192)) { - return undefined; - } - case 220: - case 221: - case 148: - case 149: - case 150: - var name_37 = node.flags && (node.flags & 512) && !node.name ? "default" : - node.kind === 148 ? "constructor" : - ts.declarationNameToString(node.name); - return getNavBarItem(name_37, getScriptKindForElementKind(node.kind), [getNodeSpan(node)]); - case 179: - case 180: - case 192: - return getDefineModuleItem(node) || getFunctionOrClassExpressionItem(node); - case 147: - var methodDecl = node; - return getNavBarItem(ts.declarationNameToString(methodDecl.name), ts.ScriptElementKind.memberFunctionElement, [getNodeSpan(node)]); - case 235: - return getNavBarItem("default", ts.ScriptElementKind.variableElement, [getNodeSpan(node)]); - case 231: - if (!node.name) { - return undefined; - } - case 234: - case 232: - case 238: - if (node.kind === 238) { - if (!node.parent.parent.moduleSpecifier && !node.propertyName) { - return undefined; - } - } - var decl = node; - if (!decl.name) { - return undefined; - } - var declName = ts.declarationNameToString(decl.name); - return getNavBarItem(declName, ts.ScriptElementKind.constElement, [getNodeSpan(node)]); - case 279: - if (node.name) { - return getNavBarItem(node.name.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69) { - return getNavBarItem(nameIdentifier.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - } - } - } - default: - return undefined; - } - } - function getNavBarItem(text, kind, spans, kindModifiers) { - if (kindModifiers === void 0) { kindModifiers = ts.ScriptElementKindModifier.none; } - return { - text: text, kind: kind, kindModifiers: kindModifiers, spans: spans, childItems: [], indent: indent, bolded: false, grayed: false - }; - } - function getDefineModuleItem(node) { - if (node.kind !== 179 && node.kind !== 180) { - return undefined; - } - if (node.parent.kind !== 174) { - return undefined; - } - var callExpr = node.parent; - if (callExpr.expression.kind !== 69 || callExpr.expression.getText() !== "define") { - return undefined; - } - var defaultName = node.getSourceFile().fileName; - if (callExpr.arguments[0].kind === 9) { - defaultName = (callExpr.arguments[0]).text; - } - return getNavBarItem(defaultName, ts.ScriptElementKind.moduleElement, [getNodeSpan(node.parent)]); - } - function getFunctionOrClassExpressionItem(node) { - if (node.kind !== 179 && - node.kind !== 180 && - node.kind !== 192) { - return undefined; - } - var fnExpr = node; - var fnName; - if (fnExpr.name && ts.getFullWidth(fnExpr.name) > 0) { - fnName = ts.declarationNameToString(fnExpr.name); - } - else { - if (fnExpr.parent.kind === 218) { - fnName = ts.declarationNameToString(fnExpr.parent.name); - } - else if (fnExpr.parent.kind === 187 && - fnExpr.parent.operatorToken.kind === 56) { - fnName = fnExpr.parent.left.getText(); - } - else if (fnExpr.parent.kind === 253 && - fnExpr.parent.name) { - fnName = fnExpr.parent.name.getText(); + ts.Debug.assert(!!variableDeclarationNode); } else { - fnName = node.kind === 192 ? anonClassText : anonFnText; + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; } - } - var scriptKind = node.kind === 192 ? ts.ScriptElementKind.classElement : ts.ScriptElementKind.functionElement; - return getNavBarItem(fnName, scriptKind, [getNodeSpan(node)]); - } - function getNodeSpan(node) { - return node.kind === 256 - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getScriptKindForElementKind(kind) { - switch (kind) { - case 218: + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { return ts.ScriptElementKind.variableElement; - case 220: - return ts.ScriptElementKind.functionElement; - case 221: - return ts.ScriptElementKind.classElement; - case 148: - return ts.ScriptElementKind.constructorImplementationElement; - case 149: - return ts.ScriptElementKind.memberGetAccessorElement; - case 150: - return ts.ScriptElementKind.memberSetAccessorElement; - default: - return "unknown"; - } + } + case 180: + return ts.ScriptElementKind.functionElement; + case 279: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); } - return sourceFileItem.childItems; } - NavigationBar.getJsNavigationBarItems = getJsNavigationBarItems; + function getModuleName(moduleDeclaration) { + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + var result = []; + result.push(moduleDeclaration.name.text); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { + moduleDeclaration = moduleDeclaration.body; + result.push(moduleDeclaration.name.text); + } + return result.join("."); + } + function getInteriorModule(decl) { + return decl.body.kind === 225 ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 140; + } + function getNodeSpan(node) { + return node.kind === 256 + ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) + : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); + } + function getFunctionOrClassName(node) { + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + else if (node.parent.kind === 218) { + return ts.declarationNameToString(node.parent.name); + } + else if (node.parent.kind === 187 && + node.parent.operatorToken.kind === 56) { + return nodeText(node.parent.left); + } + else if (node.parent.kind === 253 && node.parent.name) { + return nodeText(node.parent.name); + } + else if (node.flags & 512) { + return "default"; + } + else { + return ts.isClassLike(node) ? "" : ""; + } + } + function isFunctionOrClassExpression(node) { + return node.kind === 179 || node.kind === 180 || node.kind === 192; + } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); var ts; @@ -40372,9 +40989,9 @@ var ts; getTypingNamesFromNodeModuleFolder(nodeModulesPath); } getTypingNamesFromSourceFileNames(fileNames); - for (var name_38 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_38) && !inferredTypings[name_38]) { - inferredTypings[name_38] = packageNameToTypingLocation[name_38]; + for (var name_39 in packageNameToTypingLocation) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { @@ -40442,9 +41059,9 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, "*.json", undefined, 2); - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); if (ts.getBaseFileName(normalizedFileName) !== "package.json") { continue; @@ -41032,9 +41649,9 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_39 in o) { - if (o[name_39] === rule) { - return name_39; + for (var name_40 in o) { + if (o[name_40] === rule) { + return name_40; } } throw new Error("Unknown rule"); @@ -42880,8 +43497,8 @@ var ts; var list = createNode(282, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -43007,7 +43624,7 @@ var ts; } addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); } - if (declaration.kind === 225 && declaration.body.kind === 225) { + if (declaration.kind === 225 && declaration.body && declaration.body.kind === 225) { return; } if ((declaration.kind === 179 || declaration.kind === 180) && @@ -43706,9 +44323,9 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptions_stringToEnum; + var commandLineOptionsStringToEnum; function fixupCompilerOptions(options, diagnostics) { - commandLineOptions_stringToEnum = commandLineOptions_stringToEnum || ts.filter(ts.optionDeclarations, function (o) { + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); @@ -43726,8 +44343,8 @@ var ts; } } }; - for (var _i = 0, commandLineOptions_stringToEnum_1 = commandLineOptions_stringToEnum; _i < commandLineOptions_stringToEnum_1.length; _i++) { - var opt = commandLineOptions_stringToEnum_1[_i]; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; _loop_2(opt); } return options; @@ -43739,6 +44356,16 @@ var ts; options.suppressOutputPathCheck = true; options.allowNonTsExtensions = true; options.noLib = true; + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; options.noResolve = true; var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); var sourceFile = ts.createSourceFile(inputFileName, input, options.target); @@ -43768,7 +44395,8 @@ var ts; getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; } + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -43837,7 +44465,7 @@ var ts; var buckets = {}; var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + settings.typesRoot + "|" + settings.typesSearchPaths + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); + return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = ts.lookUp(buckets, key); @@ -44487,7 +45115,8 @@ var ts; oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs); + oldSettings.allowJs !== newSettings.allowJs || + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); var compilerHost = { getSourceFile: getOrCreateSourceFile, getSourceFileByPath: getOrCreateSourceFileByPath, @@ -44507,8 +45136,10 @@ var ts; return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); }, directoryExists: function (directoryName) { - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; } }; if (host.trace) { @@ -45164,8 +45795,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_40 = element.propertyName || element.name; - existingImportsOrExports[name_40.text] = true; + var name_41 = element.propertyName || element.name; + existingImportsOrExports[name_41.text] = true; } if (ts.isEmpty(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -45260,13 +45891,13 @@ var ts; var entries = []; var target = program.getCompilerOptions().target; var nameTable = getNameTable(sourceFile); - for (var name_41 in nameTable) { - if (nameTable[name_41] === position) { + for (var name_42 in nameTable) { + if (nameTable[name_42] === position) { continue; } - if (!uniqueNames[name_41]) { - uniqueNames[name_41] = name_41; - var displayName = getCompletionEntryDisplayName(name_41, target, true); + if (!uniqueNames[name_42]) { + uniqueNames[name_42] = name_42; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, true); if (displayName) { var entry = { name: displayName, @@ -45370,10 +46001,10 @@ var ts; var typeChecker = program.getTypeChecker(); var type = typeChecker.getContextualType(node); if (type) { - var entries_1 = []; - addStringLiteralCompletionsFromType(type, entries_1); - if (entries_1.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_1 }; + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -46572,7 +47203,8 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference + isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isDefinition: false }); } } @@ -46853,7 +47485,8 @@ var ts; references: [{ fileName: sourceFile.fileName, textSpan: ts.createTextSpan(position, searchText.length), - isWriteAccess: false + isWriteAccess: false, + isDefinition: false }] }); } @@ -47231,7 +47864,8 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node) + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) }; } function isWriteAccess(node) { @@ -47452,7 +48086,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); + return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -47831,7 +48465,8 @@ var ts; return; case 142: if (token.parent.name === token) { - return 17; + var isThis = token.kind === 69 && token.originalKeywordKind === 97; + return isThis ? 3 : 17; } return; } @@ -49028,7 +49663,7 @@ var ts; Session.prototype.getDefinition = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49046,7 +49681,7 @@ var ts; Session.prototype.getTypeDefinition = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49064,7 +49699,7 @@ var ts; Session.prototype.getOccurrences = function (line, offset, fileName) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49088,7 +49723,7 @@ var ts; Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49115,8 +49750,12 @@ var ts; Session.prototype.getProjectInfo = function (fileName, needFileNameList) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); + if (!project) { + throw Errors.NoProject; + } var projectInfo = { - configFileName: project.projectFilename + configFileName: project.projectFilename, + languageServiceDisabled: project.languageServiceDiabled }; if (needFileNameList) { projectInfo.fileNames = project.getFileNames(); @@ -49127,10 +49766,11 @@ var ts; var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - if (!projects.length) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var defaultProject = projects[0]; + var defaultProject = projectsWithLanguageServiceEnabeld[0]; var defaultProjectCompilerService = defaultProject.compilerService; var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); @@ -49143,7 +49783,7 @@ var ts; locs: [] }; } - var fileSpans = server.combineProjectOutput(projects, function (project) { + var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); if (!renameLocations) { @@ -49195,10 +49835,11 @@ var ts; var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - if (!projects.length) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var defaultProject = projects[0]; + var defaultProject = projectsWithLanguageServiceEnabeld[0]; var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); if (!nameInfo) { @@ -49208,7 +49849,7 @@ var ts; var nameSpan = nameInfo.textSpan; var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset; var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projects, function (project) { + var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var references = compilerService.languageService.getReferencesAtPosition(file, position); if (!references) { @@ -49224,7 +49865,8 @@ var ts; start: start, lineText: lineText, end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition }; }); }, compareFileStart, areReferencesResponseItemsForTheSameLocation); @@ -49253,7 +49895,7 @@ var ts; Session.prototype.getQuickInfo = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49276,7 +49918,7 @@ var ts; Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49297,7 +49939,7 @@ var ts; Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49360,7 +50002,7 @@ var ts; } var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49379,7 +50021,7 @@ var ts; Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49395,7 +50037,7 @@ var ts; Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49422,7 +50064,7 @@ var ts; var checkList = fileNames.reduce(function (accum, fileName) { fileName = ts.normalizePath(fileName); var project = _this.projectService.getProjectForFile(fileName); - if (project) { + if (project && !project.languageServiceDiabled) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -49435,7 +50077,7 @@ var ts; var _this = this; var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { var compilerService = project.compilerService; var start = compilerService.host.lineOffsetToPosition(file, line, offset); var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); @@ -49452,7 +50094,7 @@ var ts; var file = ts.normalizePath(fileName); var tmpfile = ts.normalizePath(tempFileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { this.changeSeq++; project.compilerService.host.reloadScript(file, tmpfile, function () { _this.output(undefined, CommandNames.Reload, reqSeq); @@ -49463,7 +50105,7 @@ var ts; var file = ts.normalizePath(fileName); var tmpfile = ts.normalizePath(tempFileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { project.compilerService.host.saveTo(file, tmpfile); } }; @@ -49474,7 +50116,7 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items) { + Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { var _this = this; if (!items) { return undefined; @@ -49485,17 +50127,17 @@ var ts; kind: item.kind, kindModifiers: item.kindModifiers, spans: item.spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(fileName, span.start), - end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span)) + start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), + end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems), + childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), indent: item.indent }); }); }; Session.prototype.getNavigationBarItems = function (fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49503,17 +50145,17 @@ var ts; if (!items) { return undefined; } - return this.decorateNavigationBarItem(project, fileName, items); + return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); }; Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount) { var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - var defaultProject = projects[0]; - if (!defaultProject) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var allNavToItems = server.combineProjectOutput(projects, function (project) { + var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount); if (!navItems) { @@ -49557,7 +50199,7 @@ var ts; Session.prototype.getBraceMatching = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49573,7 +50215,10 @@ var ts; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var fileNames = this.getProjectInfo(fileName, true).fileNames; + var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + if (languageServiceDisabled) { + return; + } var fileNamesInProject = fileNames.filter(function (value, index, array) { return value.indexOf("lib.d.ts") < 0; }); var highPriorityFiles = []; var mediumPriorityFiles = []; @@ -49683,6 +50328,7 @@ var ts; } }); } + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; var ScriptInfo = (function () { function ScriptInfo(host, fileName, content, isOpen) { if (isOpen === void 0) { isOpen = false; } @@ -49752,17 +50398,17 @@ var ts; var resolvedModules = []; var compilerOptions = this.getCompilationSettings(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_42 = names_2[_i]; - var resolution = ts.lookUp(newResolutions, name_42); + var name_43 = names_2[_i]; + var resolution = ts.lookUp(newResolutions, name_43); if (!resolution) { - var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_42); + var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_43); if (moduleResolutionIsValid(existingResolution)) { resolution = existingResolution; } else { - resolution = loader(name_42, containingFile, compilerOptions, this.moduleResolutionHost); + resolution = loader(name_43, containingFile, compilerOptions, this.moduleResolutionHost); resolution.lastCheckTime = Date.now(); - newResolutions[name_42] = resolution; + newResolutions[name_43] = resolution; } } ts.Debug.assert(resolution !== undefined); @@ -49898,6 +50544,9 @@ var ts; LSHost.prototype.directoryExists = function (path) { return this.host.directoryExists(path); }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; LSHost.prototype.lineToTextSpan = function (filename, line) { var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); var script = this.filenameToScript.get(path); @@ -49920,20 +50569,25 @@ var ts; var lineInfo = index.lineNumberToInfo(line); return (lineInfo.offset + offset - 1); }; - LSHost.prototype.positionToLineOffset = function (filename, position) { + LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) { + lineIndex = lineIndex || this.getLineIndex(filename); + var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + LSHost.prototype.getLineIndex = function (filename) { var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + return script.snap().index; }; return LSHost; }()); server.LSHost = LSHost; var Project = (function () { - function Project(projectService, projectOptions) { + function Project(projectService, projectOptions, languageServiceDiabled) { + if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } this.projectService = projectService; this.projectOptions = projectOptions; + this.languageServiceDiabled = languageServiceDiabled; this.directoriesWatchedForTsconfig = []; this.filenameToSourceFile = {}; this.updateGraphSeq = 0; @@ -49941,8 +50595,19 @@ var ts; if (projectOptions && projectOptions.files) { projectOptions.compilerOptions.allowNonTsExtensions = true; } - this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); + if (!languageServiceDiabled) { + this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); + } } + Project.prototype.enableLanguageService = function () { + if (this.languageServiceDiabled) { + this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions); + } + this.languageServiceDiabled = false; + }; + Project.prototype.disableLanguageService = function () { + this.languageServiceDiabled = true; + }; Project.prototype.addOpenRef = function () { this.openRefCount++; }; @@ -49954,16 +50619,36 @@ var ts; return this.projectService.openFile(filename, false); }; Project.prototype.getRootFiles = function () { + if (this.languageServiceDiabled) { + return this.projectOptions ? this.projectOptions.files : undefined; + } return this.compilerService.host.roots.map(function (info) { return info.fileName; }); }; Project.prototype.getFileNames = function () { + if (this.languageServiceDiabled) { + if (!this.projectOptions) { + return undefined; + } + var fileNames = []; + if (this.projectOptions && this.projectOptions.compilerOptions) { + fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions)); + } + ts.addRange(fileNames, this.projectOptions.files); + return fileNames; + } var sourceFiles = this.program.getSourceFiles(); return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; }); }; Project.prototype.getSourceFile = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } return this.filenameToSourceFile[info.fileName]; }; Project.prototype.getSourceFileFromName = function (filename, requireOpen) { + if (this.languageServiceDiabled) { + return undefined; + } var info = this.projectService.getScriptInfo(filename); if (info) { if ((!requireOpen) || info.isOpen) { @@ -49972,13 +50657,22 @@ var ts; } }; Project.prototype.isRoot = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } return this.compilerService.host.roots.some(function (root) { return root === info; }); }; Project.prototype.removeReferencedFile = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.removeReferencedFile(info); this.updateGraph(); }; Project.prototype.updateFileMap = function () { + if (this.languageServiceDiabled) { + return; + } this.filenameToSourceFile = {}; var sourceFiles = this.program.getSourceFiles(); for (var i = 0, len = sourceFiles.length; i < len; i++) { @@ -49987,10 +50681,16 @@ var ts; } }; Project.prototype.finishGraph = function () { + if (this.languageServiceDiabled) { + return; + } this.updateGraph(); this.compilerService.languageService.getNavigateToItems(".*"); }; Project.prototype.updateGraph = function () { + if (this.languageServiceDiabled) { + return; + } this.program = this.compilerService.languageService.getProgram(); this.updateFileMap(); }; @@ -49998,12 +50698,25 @@ var ts; return this.projectFilename; }; Project.prototype.addRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.addRoot(info); }; Project.prototype.removeRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.removeRoot(info); }; Project.prototype.filesToString = function () { + if (this.languageServiceDiabled) { + if (this.projectOptions) { + var strBuilder_1 = ""; + ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; }); + return strBuilder_1; + } + } var strBuilder = ""; ts.forEachValue(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); return strBuilder; @@ -50012,7 +50725,9 @@ var ts; this.projectOptions = projectOptions; if (projectOptions.compilerOptions) { projectOptions.compilerOptions.allowNonTsExtensions = true; - this.compilerService.setCompilerOptions(projectOptions.compilerOptions); + if (!this.languageServiceDiabled) { + this.compilerService.setCompilerOptions(projectOptions.compilerOptions); + } } }; return Project; @@ -50222,6 +50937,8 @@ var ts; if (project.isConfiguredProject()) { project.projectFileWatcher.close(); project.directoryWatcher.close(); + ts.forEachValue(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); + delete project.directoriesWatchedForWildcards; this.configuredProjects = copyListRemovingItem(project, this.configuredProjects); } else { @@ -50237,8 +50954,8 @@ var ts; this.inferredProjects = copyListRemovingItem(project, this.inferredProjects); } var fileNames = project.getFileNames(); - for (var _b = 0, fileNames_2 = fileNames; _b < fileNames_2.length; _b++) { - var fileName = fileNames_2[_b]; + for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { + var fileName = fileNames_3[_b]; var info = this.getScriptInfo(fileName); if (info.defaultProject == project) { info.defaultProject = undefined; @@ -50263,6 +50980,7 @@ var ts; else { this.findReferencingProjects(info); if (info.defaultProject) { + info.defaultProject.addOpenRef(); this.openFilesReferenced.push(info); } else { @@ -50615,12 +51333,30 @@ var ts; else { var projectOptions = { files: parsedCommandLine.fileNames, + wildcardDirectories: parsedCommandLine.wildcardDirectories, compilerOptions: parsedCommandLine.options }; return { succeeded: true, projectOptions: projectOptions }; } } }; + ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { + var totalNonTsFileSize = 0; + if (!this.host.getFileSize) { + return false; + } + for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) { + var fileName = fileNames_4[_i]; + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { var _this = this; var _a = this.configFileToProjectOptions(configFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; @@ -50628,23 +51364,39 @@ var ts; return { success: false, errors: errors }; } else { - var project_1 = this.createProject(configFilename, projectOptions); + if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { + if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + var project_1 = this.createProject(configFilename, projectOptions, true); + project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); + return { success: true, project: project_1 }; + } + } + var project_2 = this.createProject(configFilename, projectOptions); var errors_1; for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { var rootFilename = _b[_i]; if (this.host.fileExists(rootFilename)) { var info = this.openFile(rootFilename, clientFileName == rootFilename); - project_1.addRoot(info); + project_2.addRoot(info); } else { (errors_1 || (errors_1 = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); } } - project_1.finishGraph(); - project_1.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); - this.log("Add recursive watcher for: " + ts.getDirectoryPath(configFilename)); - project_1.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(configFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project_1, path); }, true); - return { success: true, project: project_1, errors: errors_1 }; + project_2.finishGraph(); + project_2.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_2); }); + var configDirectoryPath_1 = ts.getDirectoryPath(configFilename); + this.log("Add recursive watcher for: " + configDirectoryPath_1); + project_2.directoryWatcher = this.host.watchDirectory(configDirectoryPath_1, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, true); + project_2.directoriesWatchedForWildcards = ts.reduceProperties(projectOptions.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath_1, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, recursive); + } + return watchers; + }, {}); + return { success: true, project: project_2, errors: errors_1 }; } }; ProjectService.prototype.updateConfiguredProject = function (project) { @@ -50659,19 +51411,45 @@ var ts; return errors; } else { - var oldFileNames_1 = project.compilerService.host.roots.map(function (info) { return info.fileName; }); + if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + project.setProjectOptions(projectOptions); + if (project.languageServiceDiabled) { + return; + } + project.disableLanguageService(); + if (project.directoryWatcher) { + project.directoryWatcher.close(); + project.directoryWatcher = undefined; + } + return; + } + if (project.languageServiceDiabled) { + project.setProjectOptions(projectOptions); + project.enableLanguageService(); + project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); + for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { + var rootFilename = _b[_i]; + if (this.host.fileExists(rootFilename)) { + var info = this.openFile(rootFilename, false); + project.addRoot(info); + } + } + project.finishGraph(); + return; + } + var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; }); var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; }); - for (var _i = 0, fileNamesToRemove_1 = fileNamesToRemove; _i < fileNamesToRemove_1.length; _i++) { - var fileName = fileNamesToRemove_1[_i]; + for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) { + var fileName = fileNamesToRemove_1[_c]; var info = this.getScriptInfo(fileName); if (info) { project.removeRoot(info); } } - for (var _b = 0, fileNamesToAdd_1 = fileNamesToAdd; _b < fileNamesToAdd_1.length; _b++) { - var fileName = fileNamesToAdd_1[_b]; + for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) { + var fileName = fileNamesToAdd_1[_d]; var info = this.getScriptInfo(fileName); if (!info) { info = this.openFile(fileName, false); @@ -50698,8 +51476,8 @@ var ts; } } }; - ProjectService.prototype.createProject = function (projectFilename, projectOptions) { - var project = new Project(this, projectOptions); + ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { + var project = new Project(this, projectOptions, languageServiceDisabled); project.projectFilename = projectFilename; return project; }; @@ -51752,6 +52530,7 @@ var ts; function CoreServicesShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } @@ -51759,15 +52538,24 @@ var ts; this.realpath = function (path) { return _this.shimHost.realpath(path); }; } } - CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude, depth) { - var encoded; + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude), depth); + var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); } catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); + var results = []; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { + var file = _b[_a]; + if (!ts.contains(results, file)) { + results.push(file); + } + } + } + return results; } - return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -51775,6 +52563,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; + CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { + return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 533903795cf..73bf72e135e 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -713,7 +713,6 @@ declare namespace ts { } interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; - dotToken: Node; name: Identifier; } type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression; @@ -844,6 +843,7 @@ declare namespace ts { interface SwitchStatement extends Statement { expression: Expression; caseBlock: CaseBlock; + possiblyExhaustive?: boolean; } interface CaseBlock extends Node { clauses: NodeArray; @@ -919,7 +919,7 @@ declare namespace ts { type ModuleBody = ModuleBlock | ModuleDeclaration; interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; - body: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | ModuleDeclaration; } interface ModuleBlock extends Node, Statement { statements: NodeArray; @@ -1075,8 +1075,9 @@ declare namespace ts { Assignment = 16, TrueCondition = 32, FalseCondition = 64, - Referenced = 128, - Shared = 256, + SwitchClause = 128, + Referenced = 256, + Shared = 512, Label = 12, Condition = 96, } @@ -1098,6 +1099,12 @@ declare namespace ts { expression: Expression; antecedent: FlowNode; } + interface FlowSwitchClause extends FlowNode { + switchStatement: SwitchStatement; + clauseStart: number; + clauseEnd: number; + antecedent: FlowNode; + } interface AmdDependency { path: string; name: string; @@ -1132,7 +1139,13 @@ declare namespace ts { getCurrentDirectory(): string; } interface ParseConfigHost { - readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; + useCaseSensitiveFileNames: boolean; + readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[]; + /** + * Gets a value indicating whether the specified path exists and is a file. + * @param path The path to test. + */ + fileExists(path: string): boolean; } interface WriteFileCallback { (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; @@ -1412,7 +1425,6 @@ declare namespace ts { ThisType = 33554432, ObjectLiteralPatternWithComputedProperties = 67108864, Never = 134217728, - Falsy = 126, StringLike = 258, NumberLike = 132, ObjectType = 80896, @@ -1574,7 +1586,10 @@ declare namespace ts { suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; traceResolution?: boolean; + disableSizeLimit?: boolean; types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; typesSearchPaths?: string[]; [option: string]: CompilerOptionsValue | undefined; } @@ -1638,6 +1653,15 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; + wildcardDirectories?: Map; + } + enum WatchDirectoryFlags { + None = 0, + Recursive = 1, + } + interface ExpandResult { + fileNames: string[]; + wildcardDirectories: Map; } interface ModuleResolutionHost { fileExists(fileName: string): boolean; @@ -1672,6 +1696,7 @@ declare namespace ts { getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; + getDirectories(path: string): string[]; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; @@ -1707,6 +1732,7 @@ declare namespace ts { useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string; + getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; @@ -1717,7 +1743,7 @@ declare namespace ts { getExecutingFilePath(): string; getCurrentDirectory(): string; getDirectories(path: string): string[]; - readDirectory(path: string, extension?: string, exclude?: string[]): string[]; + readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; getModifiedTime?(path: string): Date; createHash?(data: string): string; getMemoryUsage?(): number; @@ -1821,6 +1847,7 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { + /** The version of the TypeScript compiler release */ const version: string; function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; @@ -1836,7 +1863,15 @@ declare namespace ts { function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function getDefaultTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; + /** + * Given a set of options and a set of root files, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -1978,6 +2013,7 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; + getDirectories?(directoryName: string): string[]; } interface LanguageService { cleanupSemanticCache(): void; @@ -2068,6 +2104,7 @@ declare namespace ts { textSpan: TextSpan; fileName: string; isWriteAccess: boolean; + isDefinition: boolean; } interface DocumentHighlights { fileName: string; diff --git a/lib/typescript.js b/lib/typescript.js index 9e41f640305..30d49888df1 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -439,8 +439,9 @@ var ts; FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; - FlowFlags[FlowFlags["Referenced"] = 128] = "Referenced"; - FlowFlags[FlowFlags["Shared"] = 256] = "Shared"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["Referenced"] = 256] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 512] = "Shared"; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; })(ts.FlowFlags || (ts.FlowFlags = {})); @@ -654,7 +655,8 @@ var ts; TypeFlags[TypeFlags["Never"] = 134217728] = "Never"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 96] = "Nullable"; - TypeFlags[TypeFlags["Falsy"] = 126] = "Falsy"; + /* @internal */ + TypeFlags[TypeFlags["Falsy"] = 112] = "Falsy"; /* @internal */ TypeFlags[TypeFlags["Intrinsic"] = 150995071] = "Intrinsic"; /* @internal */ @@ -755,6 +757,11 @@ var ts; DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; })(ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); var DiagnosticStyle = ts.DiagnosticStyle; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + var WatchDirectoryFlags = ts.WatchDirectoryFlags; /* @internal */ (function (CharacterCodes) { CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; @@ -994,6 +1001,15 @@ var ts; return -1; } ts.indexOf = indexOf; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0, len = text.length; i < len; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; function countWhere(array, predicate) { var count = 0; if (array) { @@ -1021,12 +1037,24 @@ var ts; return result; } ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + if (f(item)) { + array[outIndex] = item; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; function map(array, f) { var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result.push(f(v)); } } @@ -1045,8 +1073,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; if (!contains(result, item, areEqual)) { result.push(item); } @@ -1057,8 +1085,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var v = array_7[_i]; result += v[prop]; } return result; @@ -1383,6 +1411,30 @@ var ts; return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; } ts.compareValues = compareValues; + function compareStrings(a, b, ignoreCase) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + if (ignoreCase) { + if (String.prototype.localeCompare) { + var result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); + return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + a = a.toUpperCase(); + b = b.toUpperCase(); + if (a === b) + return 0 /* EqualTo */; + } + return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + ts.compareStrings = compareStrings; + function compareStringsCaseInsensitive(a, b) { + return compareStrings(a, b, /*ignoreCase*/ true); + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } @@ -1637,12 +1689,242 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; + /** + * Removes a trailing directory separator from a path. + * @param path The path. + */ + function removeTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) === ts.directorySeparator) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + /** + * Adds a trailing directory separator to a path, if it does not already have one. + * @param path The path. + */ + function ensureTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) !== ts.directorySeparator) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + a = removeTrailingDirectorySeparator(a); + b = removeTrailingDirectorySeparator(b); + var aComponents = getNormalizedPathComponents(a, currentDirectory); + var bComponents = getNormalizedPathComponents(b, currentDirectory); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + if (result !== 0 /* EqualTo */) { + return result; + } + } + return compareValues(aComponents.length, bComponents.length); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + parent = removeTrailingDirectorySeparator(parent); + child = removeTrailingDirectorySeparator(child); + if (parent === child) + return true; + var parentComponents = getNormalizedPathComponents(parent, currentDirectory); + var childComponents = getNormalizedPathComponents(child, currentDirectory); + if (childComponents.length < parentComponents.length) { + return false; + } + for (var i = 0; i < parentComponents.length; i++) { + var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); + if (result !== 0 /* EqualTo */) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; function fileExtensionIs(path, extension) { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsAny(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsAny = fileExtensionIsAny; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + function getRegularExpressionForWildcard(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + var pattern = ""; + var hasWrittenSubpattern = false; + spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + var spec = specs_1[_i]; + if (!spec) { + continue; + } + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + if (usage !== "exclude" && components[components.length - 1] === "**") { + continue spec; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + var optionalCount = 0; + for (var _a = 0, components_1 = components; _a < components_1.length; _a++) { + var component = components_1[_a]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + continue spec; + } + subpattern += "(/.+?)?"; + hasRecursiveDirectoryWildcard = true; + hasWrittenComponent = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + hasWrittenComponent = true; + } + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + if (hasWrittenSubpattern) { + pattern += "|"; + } + pattern += "(" + subpattern + ")"; + hasWrittenSubpattern = true; + } + if (!pattern) { + return undefined; + } + return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + } + function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var regexFlag = useCaseSensitiveFileNames ? "" : "i"; + var includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag); + var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); + var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var result = []; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + } + return result; + function visitDirectory(path, absolutePath) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; + var name_1 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!extensions || fileExtensionIsAny(name_1, extensions)) && + (!includeFileRegex || includeFileRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + result.push(name_1); + } + } + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var current = directories_1[_b]; + var name_2 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name_2, absoluteName); + } + } + } + } + ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). + var basePaths = [path]; + if (includes) { + // Storage for literal base paths amongst the include patterns. + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + if (isRootedDiskPath(include)) { + var wildcardOffset = indexOfAnyCharCode(include, wildcardCharCodes); + var includeBasePath = wildcardOffset < 0 + ? removeTrailingDirectorySeparator(getDirectoryPath(include)) + : include.substring(0, include.lastIndexOf(ts.directorySeparator, wildcardOffset)); + // Append the literal and canonical candidate base paths. + includeBasePaths.push(includeBasePath); + } + } + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path + include: for (var i = 0; i < includeBasePaths.length; i++) { + var includeBasePath = includeBasePaths[i]; + for (var j = 0; j < basePaths.length; j++) { + if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { + continue include; + } + } + basePaths.push(includeBasePath); + } + } + return basePaths; + } function ensureScriptKind(fileName, scriptKind) { // Using scriptKind as a condition handles both: // - 'scriptKind' is unspecified and thus it is `undefined` @@ -1692,6 +1974,57 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Limit"] = 5] = "Limit"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ts.ExtensionPriority || (ts.ExtensionPriority = {})); + var ExtensionPriority = ts.ExtensionPriority; + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i); + } + } + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; + } + ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ + function adjustExtensionPriority(extensionPriority) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; + } + else if (extensionPriority < 5 /* Limit */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return 5 /* Limit */; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ + function getNextLowestExtensionPriority(extensionPriority) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return 5 /* Limit */; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { @@ -1712,6 +2045,10 @@ var ts; return ext === ".jsx" || ext === ".tsx"; } ts.isJsxOrTsxExtension = isJsxOrTsxExtension; + function changeExtension(path, newExtension) { + return (removeFileExtension(path) + newExtension); + } + ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -1790,6 +2127,7 @@ var ts; ts.sys = (function () { function getWScriptSystem() { var fso = new ActiveXObject("Scripting.FileSystemObject"); + var shell = new ActiveXObject("WScript.Shell"); var fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2 /*text*/; var binaryStream = new ActiveXObject("ADODB.Stream"); @@ -1851,9 +2189,6 @@ var ts; fileStream.Close(); } } - function getCanonicalPath(path) { - return path.toLowerCase(); - } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -1865,30 +2200,19 @@ var ts; var folder = fso.GetFolder(path); return getNames(folder.subfolders); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { + function getAccessibleFileSystemEntries(path) { + try { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; - var name_1 = ts.combinePaths(path, current); - if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { - result.push(name_1); - } - } - var subfolders = getNames(folder.subfolders); - for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { - var current = subfolders_1[_a]; - var name_2 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_2))) { - visitDirectory(name_2); - } - } + var directories = getNames(folder.subfolders); + return { files: files, directories: directories }; } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } return { args: args, @@ -1917,7 +2241,7 @@ var ts; return WScript.ScriptFullName; }, getCurrentDirectory: function () { - return new ActiveXObject("WScript.Shell").CurrentDirectory; + return shell.CurrentDirectory; }, getDirectories: getDirectories, readDirectory: readDirectory, @@ -2056,8 +2380,41 @@ var ts; } } } - function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path : path.toLowerCase(); + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var entry = entries_1[_i]; + // This is necessary because on some file system node fails to exclude + // "." and "..". See https://github.com/nodejs/node/issues/4002 + if (entry === "." || entry === "..") { + continue; + } + var name_3 = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name_3); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } var FileSystemEntryKind; (function (FileSystemEntryKind) { @@ -2085,40 +2442,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); }); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { - var files = _fs.readdirSync(path || ".").sort(); - var directories = []; - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var current = files_2[_i]; - // This is necessary because on some file system node fails to exclude - // "." and "..". See https://github.com/nodejs/node/issues/4002 - if (current === "." || current === "..") { - continue; - } - var name_3 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_3))) { - var stat = _fs.statSync(name_3); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name_3, extension)) { - result.push(name_3); - } - } - else if (stat.isDirectory()) { - directories.push(name_3); - } - } - } - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var current = directories_1[_a]; - visitDirectory(current); - } - } - } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -2206,6 +2529,16 @@ var ts; } return process.memoryUsage().heapUsed; }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (e) { } + return 0; + }, exit: function (exitCode) { process.exit(exitCode); }, @@ -2239,7 +2572,10 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - readDirectory: ChakraHost.readDirectory, + readDirectory: function (path, extensions, excludes, includes) { + var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, exit: ChakraHost.quit, realpath: realpath }; @@ -2409,7 +2745,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_a_binding_pattern_1187", message: "A parameter property may not be a binding pattern." }, + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, @@ -2425,7 +2761,6 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower_1204", message: "Cannot compile modules into 'es2015' when targeting 'ES5' or lower." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -2480,6 +2815,7 @@ var ts; Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -2750,6 +3086,8 @@ var ts; The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, + Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, + Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2823,6 +3161,8 @@ var ts; Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." }, Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, @@ -2996,7 +3336,6 @@ var ts; types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "property_declarations_can_only_be_used_in_a_ts_file_8014", message: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, @@ -4985,6 +5324,11 @@ var ts; (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModule(node) { + // The only kind of module that can be missing a body is a shorthand ambient module. + return node.kind === 225 /* ModuleDeclaration */ && (!node.body); + } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 /* SourceFile */ || node.kind === 225 /* ModuleDeclaration */ || @@ -5417,6 +5761,7 @@ var ts; case 157 /* ConstructorType */: return true; } + return false; } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { @@ -5839,6 +6184,18 @@ var ts; return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + /** + * Returns true if the node is a variable declaration whose initializer is a function expression. + * This function does not test if the node is in a JavaScript file or not. + */ + function isDeclarationOfFunctionExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 218 /* VariableDeclaration */) { + var declaration = s.valueDeclaration; + return declaration.initializer && declaration.initializer.kind === 179 /* FunctionExpression */; + } + return false; + } + ts.isDeclarationOfFunctionExpression = isDeclarationOfFunctionExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder function getSpecialPropertyAssignmentKind(expression) { @@ -6815,7 +7172,9 @@ var ts; ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; @@ -7175,6 +7534,10 @@ var ts; return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -7679,7 +8042,6 @@ var ts; return visitNodes(cbNodes, node.properties); case 172 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); case 173 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || @@ -8602,6 +8964,7 @@ var ts; return token === 19 /* OpenBracketToken */ || token === 15 /* OpenBraceToken */ || token === 37 /* AsteriskToken */ + || token === 22 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenIsClassOrFunction() { @@ -10703,7 +11066,7 @@ var ts; // If it wasn't then just try to parse out a '.' and report an error. var node = createNode(172 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - node.dotToken = parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } @@ -10905,7 +11268,6 @@ var ts; if (dotToken) { var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; - propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; @@ -12250,7 +12612,12 @@ var ts; else { node.name = parseLiteralNode(/*internName*/ true); } - node.body = parseModuleBlock(); + if (token === 15 /* OpenBraceToken */) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { @@ -13341,8 +13708,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -13479,8 +13846,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -13752,7 +14119,8 @@ var ts; return state_1; } else if (node.kind === 225 /* ModuleDeclaration */) { - return getModuleInstanceState(node.body); + var body = node.body; + return body ? getModuleInstanceState(body) : 1 /* Instantiated */; } else { return 1 /* Instantiated */; @@ -14232,11 +14600,6 @@ var ts; break; } } - function isNarrowableReference(expr) { - return expr.kind === 69 /* Identifier */ || - expr.kind === 97 /* ThisKeyword */ || - expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); - } function isNarrowingExpression(expr) { switch (expr.kind) { case 69 /* Identifier */: @@ -14244,7 +14607,7 @@ var ts; case 172 /* PropertyAccessExpression */: return isNarrowableReference(expr); case 174 /* CallExpression */: - return true; + return hasNarrowableArgument(expr); case 178 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); case 187 /* BinaryExpression */: @@ -14254,6 +14617,35 @@ var ts; } return false; } + function isNarrowableReference(expr) { + return expr.kind === 69 /* Identifier */ || + expr.kind === 97 /* ThisKeyword */ || + expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 172 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 /* NullKeyword */ || expr1.kind === 69 /* Identifier */ && expr1.text === "undefined") && isNarrowableOperand(expr2); + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 182 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56 /* EqualsToken */: @@ -14262,20 +14654,34 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - if (isNarrowingExpression(expr.left) && (expr.right.kind === 93 /* NullKeyword */ || expr.right.kind === 69 /* Identifier */)) { - return true; - } - if (expr.left.kind === 182 /* TypeOfExpression */ && isNarrowingExpression(expr.left.expression) && expr.right.kind === 9 /* StringLiteral */) { - return true; - } - return false; + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91 /* InstanceOfKeyword */: - return isNarrowingExpression(expr.left); + return isNarrowableOperand(expr.left); case 24 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 178 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 187 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 56 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 24 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4 /* BranchLabel */, @@ -14290,7 +14696,7 @@ var ts; } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & 128 /* Referenced */ ? 256 /* Shared */ : 128 /* Referenced */; + flow.flags |= flow.flags & 256 /* Referenced */ ? 512 /* Shared */ : 256 /* Referenced */; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { @@ -14315,8 +14721,21 @@ var ts; setFlowNodeReferenced(antecedent); return { flags: flags, - antecedent: antecedent, - expression: expression + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingSwitchStatement(switchStatement)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128 /* SwitchClause */, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { @@ -14527,9 +14946,12 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasNonEmptyDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 /* DefaultClause */ && c.statements.length; }); - if (!hasNonEmptyDefault) { - addAntecedent(postSwitchLabel, preSwitchCaseFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); } currentBreakTarget = saveBreakTarget; preSwitchCaseFlow = savePreSwitchCaseFlow; @@ -14537,25 +14959,22 @@ var ts; } function bindCaseBlock(node) { var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { - var clause = clauses[i]; - if (clause.statements.length) { - if (currentFlow.flags & 1 /* Unreachable */) { - currentFlow = preSwitchCaseFlow; - } - else { - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, preSwitchCaseFlow); - addAntecedent(preCaseLabel, currentFlow); - currentFlow = finishFlowLabel(preCaseLabel); - } - bind(clause); - if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; } - else { - bind(clause); + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } } @@ -14855,7 +15274,7 @@ var ts; } function hasExportDeclarations(node) { var body = node.kind === 256 /* SourceFile */ ? node : node.body; - if (body.kind === 256 /* SourceFile */ || body.kind === 226 /* ModuleBlock */) { + if (body && (body.kind === 256 /* SourceFile */ || body.kind === 226 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; if (stat.kind === 236 /* ExportDeclaration */ || stat.kind === 235 /* ExportAssignment */) { @@ -15471,7 +15890,7 @@ var ts; constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; var funcSymbol = container.locals[constructorFunction.text]; - if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */)) { + if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return; } // Set up the members collection if it doesn't exist already @@ -16193,7 +16612,8 @@ var ts; var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if (modulekind || (!compilerOptions.outFile && !compilerOptions.out)) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out)) { // nodes are in different files and order cannot be determines return true; } @@ -16458,7 +16878,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -16532,6 +16953,29 @@ var ts; } return false; } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 /* Identifier */ || kind === 172 /* PropertyAccessExpression */) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194 /* ExpressionWithTypeArguments */) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0); // Block-scoped variables cannot be used before their definition @@ -16579,9 +17023,11 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = moduleSymbol.exports["export="] ? - getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : - resolveSymbol(moduleSymbol.exports["default"]); + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + moduleSymbol : + moduleSymbol.exports["export="] ? + getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : + resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -16650,6 +17096,9 @@ var ts; if (targetSymbol) { var name_10 = specifier.propertyName || specifier.name; if (name_10.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + return moduleSymbol; + } var symbolFromVariable = void 0; // First check if module was specified with "export=". If so, get the member from the resolved type if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { @@ -18171,6 +18620,9 @@ var ts; function isTypeAny(type) { return type && (type.flags & 1 /* Any */) !== 0; } + function isTypeNever(type) { + return type && (type.flags & 134217728 /* Never */) !== 0; + } // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. function getTypeForBindingElementParent(node) { @@ -18491,23 +18943,26 @@ var ts; if (declaration.kind === 235 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } - // Handle module.exports = expr - if (declaration.kind === 187 /* BinaryExpression */) { - return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - if (declaration.kind === 172 /* PropertyAccessExpression */) { - // Declarations only exist for property access expressions for certain - // special assignment kinds - if (declaration.parent.kind === 187 /* BinaryExpression */) { - // Handle exports.p = expr or this.p = expr or className.prototype.method = expr - return links.type = checkExpressionCached(declaration.parent.right); - } - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + var type = undefined; + // Handle module.exports = expr or this.p = expr + if (declaration.kind === 187 /* BinaryExpression */) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + else if (declaration.kind === 172 /* PropertyAccessExpression */) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === 187 /* BinaryExpression */) { + // Handle exports.p = expr or className.prototype.method = expr + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + } if (!popTypeResolution()) { if (symbol.valueDeclaration.type) { // Variable has type annotation that circularly references the variable itself @@ -18600,9 +19055,14 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var type = createObjectType(65536 /* Anonymous */, symbol); - links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? - addTypeKind(type, 32 /* Undefined */) : type; + if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + links.type = anyType; + } + else { + var type = createObjectType(65536 /* Anonymous */, symbol); + links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? + addTypeKind(type, 32 /* Undefined */) : type; + } } return links.type; } @@ -19660,7 +20120,7 @@ var ts; } return result; } - function isOptionalParameter(node) { + function isJSDocOptionalParameter(node) { if (node.flags & 134217728 /* JavaScriptFile */) { if (node.type && node.type.kind === 268 /* JSDocOptionalType */) { return true; @@ -19675,7 +20135,9 @@ var ts; } } } - if (ts.hasQuestionToken(node)) { + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -19734,7 +20196,7 @@ var ts; if (param.type && param.type.kind === 166 /* StringLiteralType */) { hasStringLiterals = true; } - if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { minArgumentCount = i - (hasThisParameter ? 1 : 0); } @@ -20818,6 +21280,9 @@ var ts; function isTypeComparableTo(source, target) { return checkTypeComparableTo(source, target, /*errorNode*/ undefined); } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } @@ -21897,8 +22362,10 @@ var ts; function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralType(type) { - return type.flags & 256 /* StringLiteral */; + function isStringLiteralUnionType(type) { + return type.flags & 256 /* StringLiteral */ ? true : + type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } /** * Check if a Type was written as a tuple type literal. @@ -22709,6 +23176,31 @@ var ts; } return node; } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 249 /* CaseClause */) { + var expr = clause.expression; + return expr.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + } + return undefined; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + // If all case clauses specify expressions that have unit types, we return an array + // of those unit types. Otherwise we return an empty array. + var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256 /* StringLiteral */; }) ? types : emptyArray; + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 16384 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function filterType(type, f) { + return type.flags & 16384 /* Union */ ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175 /* Narrowable */)) { @@ -22724,7 +23216,7 @@ var ts; return result; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 256 /* Shared */) { + if (flow.flags & 512 /* Shared */) { // We cache results of flow type resolution for shared nodes that were previously visited in // the same getFlowTypeOfReference invocation. A node is considered shared when it is the // antecedent of more than one node. @@ -22745,6 +23237,9 @@ var ts; else if (flow.flags & 96 /* Condition */) { type = getTypeAtFlowCondition(flow); } + else if (flow.flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } else if (flow.flags & 12 /* Label */) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; @@ -22769,7 +23264,7 @@ var ts; // simply return the declared type to reduce follow-on errors. type = declaredType; } - if (flow.flags & 256 /* Shared */) { + if (flow.flags & 512 /* Shared */) { // Record visited node and the associated type in the cache. visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; @@ -22825,6 +23320,10 @@ var ts; } return type; } + function getTypeAtSwitchClause(flow) { + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { @@ -22903,11 +23402,26 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - if (isNullOrUndefinedLiteral(expr.right)) { - return narrowTypeByNullCheck(type, expr, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (expr.left.kind === 182 /* TypeOfExpression */ && expr.right.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, expr, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + } + if (left.kind === 182 /* TypeOfExpression */ && right.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + } + if (right.kind === 182 /* TypeOfExpression */ && left.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + } + if (left.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + } + if (right.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91 /* InstanceOfKeyword */: @@ -22917,54 +23431,100 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, expr, assumeTrue) { - // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' on the right - var operator = expr.operatorToken.kind; + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' as value if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(expr.left))) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; var facts = doubleEquals ? assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - expr.right.kind === 93 /* NullKeyword */ ? + literal.kind === 93 /* NullKeyword */ ? assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - function narrowTypeByTypeof(type, expr, assumeTrue) { - // We have '==', '!=', '====', or !==' operator with 'typeof xxx' on the left - // and string literal on the right - var left = getReferenceFromExpression(expr.left.expression); - var right = expr.right; - if (!isMatchingReference(reference, left)) { + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands + var target = getReferenceFromExpression(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { + if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (expr.operatorToken.kind === 31 /* ExclamationEqualsToken */ || - expr.operatorToken.kind === 33 /* ExclamationEqualsEqualsToken */) { + if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } if (assumeTrue && !(type.flags & 16384 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primtive type. For example, type 'any' can be narrowed // to one of the primitive types. - var targetType = ts.getProperty(typeofTypesByName, right.text); + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, right.text) || 64 /* TypeofEQHostObject */ : - ts.getProperty(typeofNEFacts, right.text) || 8192 /* TypeofNEHostObject */; + ts.getProperty(typeofEQFacts, literal.text) || 64 /* TypeofEQHostObject */ : + ts.getProperty(typeofNEFacts, literal.text) || 8192 /* TypeofNEHostObject */; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with property access as target + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256 /* StringLiteral */) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We have switch statement with property access expression + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { @@ -23836,9 +24396,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } - function contextualTypeIsStringLiteralType(type) { - return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); - } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); @@ -24839,7 +25396,7 @@ var ts; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { - if (right.text) { + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 /* ThisType */ ? apparentType : type)); } return unknownType; @@ -26126,8 +26683,12 @@ var ts; // When resolved signature is a call signature (and not a construct signature) the result type is any, unless // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations // in a JS file - var funcSymbol = checkExpression(node.expression).symbol; - if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */)) { + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = node.expression.kind === 69 /* Identifier */ ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return getInferredClassType(funcSymbol); } else if (compilerOptions.noImplicitAny) { @@ -26147,6 +26708,7 @@ var ts; } function checkAssertion(node) { var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); @@ -26264,6 +26826,14 @@ var ts; } return emptyObjectType; } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { @@ -26297,19 +26867,12 @@ var ts; else { types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { - return neverType; + // For an async function, the return type will not be never, but rather a Promise for never. + return isAsync ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - if (isAsync) { - // For an async function, the return type will not be void, but rather a Promise for void. - var promiseType = createPromiseType(voidType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - return voidType; + // For an async function, the return type will not be void, but rather a Promise for void. + return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } // When yield/return statements are contextually typed we allow the return type to be a union type. @@ -26323,7 +26886,7 @@ var ts; else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience - return getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -26334,20 +26897,10 @@ var ts; reportErrorsFromWidening(func, type); } var widenedType = getWidenedType(type); - if (isAsync) { - // From within an async function you can return either a non-promise value or a promise. Any - // Promise/A+ compatible implementation will always assimilate any foreign promise, so the - // return type of the body is awaited type of the body, wrapped in a native Promise type. - var promiseType = createPromiseType(widenedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - else { - return widenedType; - } + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; @@ -26366,10 +26919,40 @@ var ts; }); return aggregatedTypes; } + function isExhaustiveSwitchStatement(node) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172 /* PropertyAccessExpression */) { + return false; + } + var type = checkExpression(expr.expression); + if (!(type.flags & 16384 /* Union */)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(propType, switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 32768 /* HasImplicitReturn */)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 213 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasReturnWithNoExpression = !!(func.flags & 32768 /* HasImplicitReturn */); + var hasReturnWithNoExpression = functionHasImplicitReturn(func); var hasReturnOfTypeNever = false; ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; @@ -26423,7 +27006,7 @@ var ts; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 /* Block */ || !(func.flags & 32768 /* HasImplicitReturn */)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 65536 /* HasExplicitReturn */; @@ -27016,7 +27599,7 @@ var ts; case 90 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); case 51 /* AmpersandAmpersandToken */: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 126 /* Falsy */) : rightType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112 /* Falsy */) : rightType; case 52 /* BarBarToken */: return getUnionType([getNonNullableType(leftType), rightType]); case 56 /* EqualsToken */: @@ -27132,7 +27715,7 @@ var ts; } function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + if (contextualType && isStringLiteralUnionType(contextualType)) { return getStringLiteralTypeForText(node.text); } return stringType; @@ -27979,9 +28562,6 @@ var ts; } } } - // when checking exported function declarations across modules check only duplicate implementations - // names and consistency of modifiers are verified when we check local symbol - var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536 /* Module */; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { @@ -28013,7 +28593,7 @@ var ts; duplicateFunctionDeclaration = true; } } - else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } if (ts.nodeIsPresent(node.body)) { @@ -28041,7 +28621,7 @@ var ts; }); } // Abstract methods can't have an implementation -- in particular, they don't need one. - if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !(lastSeenNonAmbientDeclaration.flags & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -28142,7 +28722,7 @@ var ts; } function checkNonThenableType(type, location, message) { type = getWidenedType(type); - if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) { if (location) { if (!message) { message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; @@ -28168,37 +28748,39 @@ var ts; // ): any; // } // - if (promise.flags & 1 /* Any */) { + if (isTypeAny(promise)) { return undefined; } - if ((promise.flags & 4096 /* Reference */) && promise.target === tryGetGlobalPromiseType()) { - return promise.typeArguments[0]; + if (promise.flags & 4096 /* Reference */) { + if (promise.target === tryGetGlobalPromiseType() + || promise.target === getGlobalPromiseLikeType()) { + return promise.typeArguments[0]; + } } var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (thenFunction && (thenFunction.flags & 1 /* Any */)) { + if (!thenFunction || isTypeAny(thenFunction)) { return undefined; } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray; + var thenSignatures = getSignaturesOfType(thenFunction, 0 /* Call */); if (thenSignatures.length === 0) { return undefined; } var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072 /* NEUndefined */); - if (onfulfilledParameterType.flags & 1 /* Any */) { + if (isTypeAny(onfulfilledParameterType)) { return undefined; } var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); - return valueParameterType; + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { - return getTypeAtPosition(signature, 0); + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; } /** * Gets the "awaited type" of a type. @@ -30189,7 +30771,7 @@ var ts; // - augmentation for a global scope is always applied // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Merged */); - if (checkBody) { + if (checkBody && node.body) { // body of ambient external module is always a module block for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; @@ -30217,7 +30799,13 @@ var ts; } } } - checkSourceElement(node.body); + if (compilerOptions.noImplicitAny && !node.body) { + // Ambient shorthand module is an implicit any + reportImplicitAnyError(node, anyType); + } + if (node.body) { + checkSourceElement(node.body); + } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { @@ -31982,7 +32570,10 @@ var ts; return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 142 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 142 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); @@ -33812,21 +34403,26 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body.kind !== 226 /* ModuleBlock */) { + while (node.body && node.body.kind !== 226 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; + if (node.body) { + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + else { + write(";"); + } } function writeTypeAliasDeclaration(node) { var prevEnclosingDeclaration = enclosingDeclaration; @@ -36393,7 +36989,6 @@ var ts; function createPropertyAccessExpression(expression, name) { var result = ts.createSynthesizedNode(172 /* PropertyAccessExpression */); result.expression = parenthesizeForAccess(expression); - result.dotToken = ts.createSynthesizedNode(21 /* DotToken */); result.name = name; return result; } @@ -36457,9 +37052,9 @@ var ts; emit(node.initializer); } // Return true if identifier resolves to an exported member of a namespace - function isNamespaceExportReference(node) { + function isExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 256 /* SourceFile */; + return !!container; } // Return true if identifier resolves to an imported identifier function isImportedReference(node) { @@ -36490,10 +37085,10 @@ var ts; // const foo_1 = require('./foo'); // exports.baz = { foo: foo_1.foo }; // - if (languageVersion < 2 /* ES6 */ || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isNamespaceExportReference(node.name)) { + if (languageVersion < 2 /* ES6 */ || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { // Emit identifier as an identifier write(": "); - emit(node.name); + emitExpressionIdentifier(node.name); } if (languageVersion >= 2 /* ES6 */ && node.objectAssignmentInitializer) { write(" = "); @@ -36552,7 +37147,10 @@ var ts; return; } emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; + var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; + var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); // 1 .toString is a valid property access, emit a space after the literal // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal var shouldEmitSpace = false; @@ -36575,7 +37173,7 @@ var ts; else { write("."); } - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -37014,7 +37612,6 @@ var ts; synthesizedLHS = ts.createSynthesizedNode(172 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; - synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; write(", "); } @@ -39556,7 +40153,11 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { + var isES6ExportedClass = isES6ExportedDeclaration(node); if (node.kind === 221 /* ClassDeclaration */) { + if (isES6ExportedClass && !(node.flags & 512 /* Default */)) { + write("export "); + } // source file level classes in system modules are hoisted so 'var's for them are already defined if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); @@ -39621,9 +40222,15 @@ var ts; write(";"); } emitEnd(node); - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 221 /* ClassDeclaration */ && !isES6ExportedClass) { emitExportMemberAssignment(node); } + else if (isES6ExportedClass && (node.flags & 512 /* Default */)) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); @@ -40000,10 +40607,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 160 /* ArrayType */) { + if (parameterType && parameterType.kind === 160 /* ArrayType */) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 155 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType && parameterType.kind === 155 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -40021,9 +40628,15 @@ var ts; } /** Serializes the return type of function. Used by the __metadata decorator for a method. */ function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node) && node.type) { - emitSerializedTypeNode(node.type); - return; + if (node && ts.isFunctionLike(node)) { + if (node.type) { + emitSerializedTypeNode(node.type); + return; + } + else if (ts.isAsyncFunctionLike(node)) { + write("Promise"); + return; + } } write("void 0"); } @@ -40162,7 +40775,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + if (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -40204,6 +40817,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); + ts.Debug.assert(node.body !== undefined); // node.body must exist, as this is a non-ambient module if (node.body.kind === 226 /* ModuleBlock */) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; @@ -41998,13 +42612,9 @@ var ts; /* @internal */ ts.ioReadTime = 0; /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ - var emptyArray = []; - var defaultLibrarySearchPaths = [ - "types/", - "node_modules/", - "node_modules/@types/", - ]; ts.version = "1.9.0"; + var emptyArray = []; + var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { while (true) { var fileName = ts.combinePaths(searchPath, "tsconfig.json"); @@ -42144,6 +42754,10 @@ var ts; return undefined; } var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + return options.typeRoots || + ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(), d); }); + } /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups @@ -42157,37 +42771,35 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - // use typesRoot and fallback to directory that contains tsconfig or current directory if typesRoot is not set - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); + var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; // Check primary library paths - if (rootDir !== undefined) { - var effectivePrimarySearchPaths = options.typesSearchPaths || defaultLibrarySearchPaths; - for (var _i = 0, effectivePrimarySearchPaths_1 = effectivePrimarySearchPaths; _i < effectivePrimarySearchPaths_1.length; _i++) { - var searchPath = effectivePrimarySearchPaths_1[_i]; - var primaryPath = ts.combinePaths(rootDir, searchPath); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, primaryPath); - } - var candidate = ts.combinePaths(primaryPath, typeReferenceDirectiveName); + if (typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { @@ -42211,9 +42823,6 @@ var ts; if (containingFile) { initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); } - else { - initialLocationForSecondaryLookup = rootDir; - } if (initialLocationForSecondaryLookup !== undefined) { // check secondary locations if (traceEnabled) { @@ -42808,25 +43417,12 @@ var ts; } } } - function getDefaultTypeDirectiveNames(rootPath) { - var localTypes = ts.combinePaths(rootPath, "types"); - var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); - var result = []; - if (ts.sys.directoryExists(localTypes)) { - result = result.concat(ts.sys.getDirectories(localTypes)); - } - if (ts.sys.directoryExists(npmTypes)) { - result = result.concat(ts.sys.getDirectories(npmTypes)); - } - return result; - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { - getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -42839,6 +43435,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; } @@ -42894,21 +43491,36 @@ var ts; } return resolutions; } - function getDefaultTypeDirectiveNames(options, rootFiles, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + /** + * Given a set of options and a set of root files, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { // Use explicit type list from tsconfig.json if (options.types) { return options.types; } - // or load all types from the automatic type import fields - if (host && host.getDefaultTypeDirectiveNames) { - var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - if (commonRoot) { - return host.getDefaultTypeDirectiveNames(commonRoot); + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + result = result.concat(host.getDirectories(root)); + } } } - return undefined; + return result; } - ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -42948,10 +43560,12 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); - // load type declarations specified via 'types' argument - var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, /*containingFile*/ undefined); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); } @@ -43026,8 +43640,8 @@ var ts; // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = {}; - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var sourceFile = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -43048,10 +43662,9 @@ var ts; (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs) || (oldOptions.rootDir !== options.rootDir) || - (oldOptions.typesSearchPaths !== options.typesSearchPaths) || (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.typesRoot !== options.typesRoot) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; @@ -43383,8 +43996,20 @@ var ts; } break; case 145 /* PropertyDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; + var propertyDeclaration = node; + if (propertyDeclaration.modifiers) { + for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 113 /* StaticKeyword */) { + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + } + } + } + if (checkTypeAnnotation(node.type)) { + return true; + } + break; case 224 /* EnumDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; @@ -43530,10 +44155,13 @@ var ts; // This type of declaration is permitted only in the global module. // The StringLiteral must specify a top - level external module name. // Relative external module names are not permitted - // NOTE: body of ambient module is always a module block - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, /*inAmbientModule*/ true); + // NOTE: body of ambient module is always a module block, if it exists + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } } } } @@ -43696,7 +44324,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_name_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); } if (saveResolution) { resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective; @@ -43868,10 +44496,6 @@ var ts; var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - // Cannot specify module gen target of es6 when below es6 - if (options.module === ts.ModuleKind.ES6 && languageVersion < 2 /* ES6 */) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); - } // Cannot specify module gen that isn't amd or system with --out if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { @@ -44278,8 +44902,13 @@ var ts; } }, { - name: "typesRoot", - type: "string" + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + } }, { name: "types", @@ -44348,6 +44977,10 @@ var ts; }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, + { + name: "disableProjectSizeLimit", + type: "boolean" + }, { name: "strictNullChecks", type: "boolean", @@ -44418,7 +45051,15 @@ var ts; ts.parseCustomTypeOption = parseCustomTypeOption; /* @internal */ function parseListTypeOption(opt, value, errors) { - var values = trimString((value || "")).split(","); + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); switch (opt.element.type) { case "number": return ts.map(values, parseInt); @@ -44478,8 +45119,11 @@ var ts; i++; break; case "list": - options[opt.name] = parseListTypeOption(opt, args[i], errors); - i++; + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } break; // If not a primitive, the possible types are specified in what is effectively a map of options. default: @@ -44590,7 +45234,7 @@ var ts; } // Skip over any minified JavaScript files (ending in ".min.js") // Skip over dotted files and folders as well - var IgnoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -44605,72 +45249,59 @@ var ts; var options = ts.extend(existingOptions, compilerOptions); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; - var fileNames = getFileNames(errors); + var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, - errors: errors + errors: errors, + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { - var fileNames = []; + var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { - fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = json["files"]; } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); } } - else { - var filesSeen = {}; - var exclude = []; - if (ts.isArray(json["exclude"])) { - exclude = json["exclude"]; + var includeSpecs; + if (ts.hasProperty(json, "include")) { + if (ts.isArray(json["include"])) { + includeSpecs = json["include"]; } else { - // by default exclude node_modules, and any specificied output directory - exclude = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - exclude.push(outDir); - } - exclude = ts.map(exclude, function (e) { return ts.getNormalizedAbsolutePath(e, basePath); }); - var supportedExtensions = ts.getSupportedExtensions(options); - ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); - // Get files of supported extensions in their order of resolution - for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; - var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); - for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { - var fileName = filesInDirWithExtension_1[_a]; - // .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension, - // lets pick them when its turn comes up - if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { - continue; - } - if (IgnoreFileNamePattern.test(fileName)) { - continue; - } - // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files) - // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation - if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { - var baseName = fileName.substr(0, fileName.length - extension.length); - if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { - continue; - } - } - filesSeen[fileName] = true; - fileNames.push(fileName); - } + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); } } - if (ts.hasProperty(json, "excludes") && !ts.hasProperty(json, "exclude")) { + var excludeSpecs; + if (ts.hasProperty(json, "exclude")) { + if (ts.isArray(json["exclude"])) { + excludeSpecs = json["exclude"]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + } + } + else if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - return fileNames; + else { + // By default, exclude common package folders + excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + } + // Always exclude the output directory unless explicitly included + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } + if (fileNames === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; @@ -44752,6 +45383,273 @@ var ts; function trimString(s) { return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path with multiple recursive directory wildcards. + * Matches **\** and **\a\**, but not **\a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \*\* # matches a recursive directory wildcard "**" + * ($|\/) # matches either the end of the string or a directory separator. + */ + var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + /** + * Expands an array of file specifications. + * + * @param fileNames The literal file names to include. + * @param include The wildcard file specifications to include. + * @param exclude The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + basePath = ts.normalizePath(basePath); + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. + var literalFileMap = {}; + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. + var wildcardFileMap = {}; + if (include) { + include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false); + } + if (exclude) { + exclude = validateSpecs(exclude, errors, /*allowTrailingRecursion*/ true); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. + var supportedExtensions = ts.getSupportedExtensions(options); + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (fileNames) { + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var file = ts.combinePaths(basePath, fileName); + literalFileMap[keyMapper(file)] = file; + } + } + if (include && include.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + var file = _b[_a]; + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + if (ignoreFileNamePattern.test(file)) { + continue; + } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + wildcardFileMap[key] = file; + } + } + } + var literalFiles = ts.reduceProperties(literalFileMap, addFileToOutput, []); + var wildcardFiles = ts.reduceProperties(wildcardFileMap, addFileToOutput, []); + wildcardFiles.sort(host.useCaseSensitiveFileNames ? ts.compareStrings : ts.compareStringsCaseInsensitive); + return { + fileNames: literalFiles.concat(wildcardFiles), + wildcardDirectories: wildcardDirectories + }; + } + function validateSpecs(specs, errors, allowTrailingRecursion) { + var validSpecs = []; + for (var _i = 0, specs_2 = specs; _i < specs_2.length; _i++) { + var spec = specs_2[_i]; + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + } + else { + validSpecs.push(spec); + } + } + return validSpecs; + } + /** + * Gets directories in a set of include patterns that should be watched for changes. + */ + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var name_35 = ts.combinePaths(path, file); + if (excludeRegex && excludeRegex.test(name_35)) { + continue; + } + var match = wildcardDirectoryPattern.exec(name_35); + if (match) { + var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); + var flags = watchRecursivePattern.test(name_35) ? 1 /* Recursive */ : 0 /* None */; + var existingFlags = ts.getProperty(wildcardDirectories, key); + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + // Remove any subpaths under an existing recursively watched directory. + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + return true; + } + } + return false; + } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + delete wildcardFiles[lowerPriorityPath]; + } + } + /** + * Adds a file to an array of files. + * + * @param output The output array. + * @param file The file path. + */ + function addFileToOutput(output, file) { + output.push(file); + return output; + } + /** + * Gets a case sensitive key. + * + * @param key The original key. + */ + function caseSensitiveKeyMapper(key) { + return key; + } + /** + * Gets a case insensitive key. + * + * @param key The original key. + */ + function caseInsensitiveKeyMapper(key) { + return key.toLowerCase(); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -44929,12 +45827,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_35 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_35); + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_35); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -44947,14 +45845,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_35); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_35, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -45100,689 +45998,586 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile, compilerOptions) { - // TODO: Handle JS files differently in 'navbar' calls for now, but ideally we should unify - // the 'navbar' and 'navto' logic for TypeScript and JavaScript. - if (ts.isSourceFileJavaScript(sourceFile)) { - return getJsNavigationBarItems(sourceFile, compilerOptions); + function getNavigationBarItems(sourceFile) { + curSourceFile = sourceFile; + var result = ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. + var curSourceFile; + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); } - return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); - function getIndent(node) { - var indent = 1; // Global node is the only one with indent 0. - var current = node.parent; - while (current) { - switch (current.kind) { - case 225 /* ModuleDeclaration */: - // If we have a module declared as A.B.C, it is more "intuitive" - // to say it only has a single layer of depth - do { - current = current.parent; - } while (current.kind === 225 /* ModuleDeclaration */); - // fall through - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: - indent++; + else { + parent.children = [child]; + } + } + /* + For performance, we keep navigation bar parents on a stack rather than passing them through each recursion. + `parent` is the current parent and is *not* stored in parentsStack. + `startNode` sets a new parent and `endNode` returns to the previous parent. + */ + var parentsStack = []; + var parent; + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + /** + * Add a new level of NavigationBarNodes. + * This pushes to the stack, so you must call `endNode` when you are done adding to this node. + */ + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + // Save the old parent + parentsStack.push(parent); + parent = navNode; + } + /** Call after calling `startNode` and adding children to it. */ + function endNode() { + if (parent.children) { + mergeChildren(parent.children); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ + function addChildrenRecursively(node) { + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 148 /* Constructor */: + // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + // Parameter properties are children of the class, not the constructor. + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } } - current = current.parent; - } - return indent; - } - function getChildNodes(nodes) { - var childNodes = []; - function visit(node) { - switch (node.kind) { - case 200 /* VariableStatement */: - ts.forEach(node.declarationList.declarations, visit); - break; - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: - ts.forEach(node.elements, visit); - break; - case 236 /* ExportDeclaration */: - // Handle named exports case e.g.: - // export {a, b as B} from "mod"; - if (node.exportClause) { - ts.forEach(node.exportClause.elements, visit); + break; + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 146 /* MethodSignature */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 231 /* ImportClause */: + var importClause = node; + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addLeafNode(importClause); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 232 /* NamespaceImport */) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); } - break; - case 230 /* ImportDeclaration */: - var importClause = node.importClause; - if (importClause) { - // Handle default import case e.g.: - // import d from "mod"; - if (importClause.name) { - childNodes.push(importClause); - } - // Handle named bindings in imports e.g.: - // import * as NS from "mod"; - // import {a, b as B} from "mod"; - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232 /* NamespaceImport */) { - childNodes.push(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, visit); - } - } - } - break; - case 169 /* BindingElement */: - case 218 /* VariableDeclaration */: - if (ts.isBindingPattern(node.name)) { - visit(node.name); - break; - } - // Fall through - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 225 /* ModuleDeclaration */: - case 220 /* FunctionDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: - case 223 /* TypeAliasDeclaration */: - childNodes.push(node); - break; + } } - } - // for (let i = 0, n = nodes.length; i < n; i++) { - // let node = nodes[i]; - // if (node.kind === SyntaxKind.ClassDeclaration || - // node.kind === SyntaxKind.EnumDeclaration || - // node.kind === SyntaxKind.InterfaceDeclaration || - // node.kind === SyntaxKind.ModuleDeclaration || - // node.kind === SyntaxKind.FunctionDeclaration) { - // childNodes.push(node); - // } - // else if (node.kind === SyntaxKind.VariableStatement) { - // childNodes.push.apply(childNodes, (node).declarations); - // } - // } - ts.forEach(nodes, visit); - return sortNodes(childNodes); - } - function getTopLevelNodes(node) { - var topLevelNodes = []; - topLevelNodes.push(node); - addTopLevelNodes(node.statements, topLevelNodes); - return topLevelNodes; - } - function sortNodes(nodes) { - return nodes.slice(0).sort(function (n1, n2) { - if (n1.name && n2.name) { - return localeCompareFix(ts.getPropertyNameForPropertyNameNode(n1.name), ts.getPropertyNameForPropertyNameNode(n2.name)); + break; + case 169 /* BindingElement */: + case 218 /* VariableDeclaration */: + var decl = node; + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } - else if (n1.name) { - return 1; - } - else if (n2.name) { - return -1; + else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { + // For `const x = function() {}`, just use the function node, not the const. + addChildrenRecursively(decl.initializer); } else { - return n1.kind - n2.kind; + addNodeWithRecursiveChild(decl, decl.initializer); } - }); - // node 0.10 treats "a" as greater than "B". - // For consistency, sort alphabetically, falling back to which is lower-case. - function localeCompareFix(a, b) { - var cmp = a.toLowerCase().localeCompare(b.toLowerCase()); - if (cmp !== 0) - return cmp; - // Return the *opposite* of the `<` operator, which works the same in node 0.10 and 6.0. - return a < b ? 1 : a > b ? -1 : 0; - } - } - function addTopLevelNodes(nodes, topLevelNodes) { - nodes = sortNodes(nodes); - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; - switch (node.kind) { - case 221 /* ClassDeclaration */: - topLevelNodes.push(node); - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 147 /* MethodDeclaration */ || member.kind === 148 /* Constructor */) { - if (member.body) { - // We do not include methods that does not have child functions in it, because of duplications. - if (hasNamedFunctionDeclarations(member.body.statements)) { - topLevelNodes.push(member); - } - addTopLevelNodes(member.body.statements, topLevelNodes); - } + break; + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + addNodeWithRecursiveChild(node, node.body); + break; + case 224 /* EnumDeclaration */: + startNode(node); + for (var _d = 0, _e = node.members; _d < _e.length; _d++) { + var member = _e[_d]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 222 /* InterfaceDeclaration */: + startNode(node); + for (var _f = 0, _g = node.members; _f < _g.length; _f++) { + var member = _g[_f]; + addChildrenRecursively(member); + } + endNode(); + break; + case 225 /* ModuleDeclaration */: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 238 /* ExportSpecifier */: + case 229 /* ImportEqualsDeclaration */: + case 153 /* IndexSignature */: + case 151 /* CallSignature */: + case 152 /* ConstructSignature */: + case 223 /* TypeAliasDeclaration */: + addLeafNode(node); + break; + default: + if (node.jsDocComments) { + for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { + var jsDocComment = _j[_h]; + for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { + var tag = _l[_k]; + if (tag.kind === 279 /* JSDocTypedefTag */) { + addLeafNode(tag); } } - break; - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - topLevelNodes.push(node); - break; - case 225 /* ModuleDeclaration */: - var moduleDeclaration = node; - topLevelNodes.push(node); - addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); - break; - case 220 /* FunctionDeclaration */: - var functionDeclaration = node; - if (isTopLevelFunctionDeclaration(functionDeclaration)) { - topLevelNodes.push(node); - addTopLevelNodes(functionDeclaration.body.statements, topLevelNodes); - } - break; + } } - } + ts.forEachChild(node, addChildrenRecursively); } - function hasNamedFunctionDeclarations(nodes) { - for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { - var s = nodes_5[_i]; - if (s.kind === 220 /* FunctionDeclaration */ && !isEmpty(s.name.text)) { + } + /** Merge declarations of the same kind. */ + function mergeChildren(children) { + var nameToItems = {}; + ts.filterMutate(children, function (child) { + var decl = child.node; + var name = decl.name && nodeText(decl.name); + if (!name) { + // Anonymous items are never merged. + return true; + } + var itemsWithSameName = ts.getProperty(nameToItems, name); + if (!itemsWithSameName) { + nameToItems[name] = child; + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child)) { + return false; + } + nameToItems[name] = [itemWithSameName, child]; + return true; + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); return true; } + return false; } - return false; - } - function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 220 /* FunctionDeclaration */) { - // A function declaration is 'top level' if it contains any function declarations - // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === 199 /* Block */) { - // Proper function declarations can only have identifier names - if (hasNamedFunctionDeclarations(functionDeclaration.body.statements)) { - return true; - } - // Or if it is not parented by another function. I.e all functions at module scope are 'top level'. - if (!ts.isFunctionBlock(functionDeclaration.parent)) { - return true; - } - else { - // We have made sure that a grand parent node exists with 'isFunctionBlock()' above. - var grandParentKind = functionDeclaration.parent.parent.kind; - if (grandParentKind === 147 /* MethodDeclaration */ || - grandParentKind === 148 /* Constructor */) { - return true; - } - } + }); + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a, b) { + return a.kind === b.kind && (a.kind !== 225 /* ModuleDeclaration */ || areSameModule(a, b)); + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a, b) { + if (a.body.kind !== b.body.kind) { + return false; } - } - return false; - } - function getItemsWorker(nodes, createItem) { - var items = []; - var keyToItem = {}; - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var child = nodes_6[_i]; - var item = createItem(child); - if (item !== undefined) { - if (item.text.length > 0) { - var key = item.text + "-" + item.kind + "-" + item.indent; - var itemWithSameName = keyToItem[key]; - if (itemWithSameName) { - // We had an item with the same name. Merge these items together. - merge(itemWithSameName, item); - } - else { - keyToItem[key] = item; - items.push(item); - } - } + if (a.body.kind !== 225 /* ModuleDeclaration */) { + return true; } + return areSameModule(a.body, b.body); } - return items; } + /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { - // First, add any spans in the source to the target. - ts.addRange(target.spans, source.spans); - if (source.childItems) { - if (!target.childItems) { - target.childItems = []; - } - // Next, recursively merge or add any children in the source as appropriate. - outer: for (var _i = 0, _a = source.childItems; _i < _a.length; _i++) { - var sourceChild = _a[_i]; - for (var _b = 0, _c = target.childItems; _b < _c.length; _b++) { - var targetChild = _c[_b]; - if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) { - // Found a match. merge them. - merge(targetChild, sourceChild); - continue outer; - } - } - // Didn't find a match, just add this child to the list. - target.childItems.push(sourceChild); - } + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); + } + var _a; + } + } + /** Recursively ensure that each NavNode's children are in sorted order. */ + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); + if (name1 && name2) { + var cmp = localeCompareFix(name1, name2); + return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + else { + return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + } + // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. + var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". + var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + // This isn't perfect, but it passes all of our tests. + for (var i = 0; i < Math.min(a.length, b.length); i++) { + var chA = a.charAt(i), chB = b.charAt(i); + if (chA === "\"" && chB === "'") { + return 1; + } + if (chA === "'" && chB === "\"") { + return -1; + } + var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + if (cmp !== 0) { + return cmp; } } - function createChildItem(node) { - switch (node.kind) { - case 142 /* Parameter */: - if (ts.isBindingPattern(node.name)) { - break; - } - if ((node.flags & 1023 /* Modifier */) === 0) { - return undefined; - } - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 149 /* GetAccessor */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 150 /* SetAccessor */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 153 /* IndexSignature */: - return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 224 /* EnumDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); - case 255 /* EnumMember */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 225 /* ModuleDeclaration */: - return createItem(node, getModuleName(node), ts.ScriptElementKind.moduleElement); - case 222 /* InterfaceDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); - case 223 /* TypeAliasDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.typeElement); - case 151 /* CallSignature */: - return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 152 /* ConstructSignature */: - return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 221 /* ClassDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.classElement); - case 220 /* FunctionDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - var variableDeclarationNode = void 0; - var name_36; - if (node.kind === 169 /* BindingElement */) { - name_36 = node.name; - variableDeclarationNode = node; - // binding elements are added only for variable declarations - // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(variableDeclarationNode !== undefined); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_36 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.constElement); - } - else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.letElement); - } - else { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.variableElement); - } - case 148 /* Constructor */: - return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 238 /* ExportSpecifier */: - case 234 /* ImportSpecifier */: - case 229 /* ImportEqualsDeclaration */: - case 231 /* ImportClause */: - case 232 /* NamespaceImport */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); - } - return undefined; - function createItem(node, name, scriptElementKind) { - return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]); - } + return a.length - b.length; + }; + /** + * This differs from getItemName because this is just used for sorting. + * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like. + * So `new()` can still come before an `aardvark` method. + */ + function tryGetName(node) { + if (node.kind === 225 /* ModuleDeclaration */) { + return getModuleName(node); } - function isEmpty(text) { - return !text || text.trim() === ""; + var decl = node; + if (decl.name) { + return ts.getPropertyNameForPropertyNameNode(decl.name); } - function getNavigationBarItem(text, kind, kindModifiers, spans, childItems, indent) { - if (childItems === void 0) { childItems = []; } - if (indent === void 0) { indent = 0; } - if (isEmpty(text)) { + switch (node.kind) { + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 192 /* ClassExpression */: + return getFunctionOrClassName(node); + case 279 /* JSDocTypedefTag */: + return getJSDocTypedefTagName(node); + default: return undefined; + } + } + function getItemName(node) { + if (node.kind === 225 /* ModuleDeclaration */) { + return getModuleName(node); + } + var name = node.name; + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; } + } + switch (node.kind) { + case 256 /* SourceFile */: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + if (node.flags & 512 /* Default */) { + return "default"; + } + return getFunctionOrClassName(node); + case 148 /* Constructor */: + return "constructor"; + case 152 /* ConstructSignature */: + return "new()"; + case 151 /* CallSignature */: + return "()"; + case 153 /* IndexSignature */: + return "[]"; + case 279 /* JSDocTypedefTag */: + return getJSDocTypedefTagName(node); + default: + ts.Debug.fail(); + return ""; + } + } + function getJSDocTypedefTagName(node) { + if (node.name) { + return node.name.text; + } + else { + var parentNode = node.parent && node.parent.parent; + if (parentNode && parentNode.kind === 200 /* VariableStatement */) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (nameIdentifier.kind === 69 /* Identifier */) { + return nameIdentifier.text; + } + } + } + return ""; + } + } + /** Flattens the NavNode tree to a list, keeping only the top-level items. */ + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 224 /* EnumDeclaration */: + case 222 /* InterfaceDeclaration */: + case 225 /* ModuleDeclaration */: + case 256 /* SourceFile */: + case 223 /* TypeAliasDeclaration */: + case 279 /* JSDocTypedefTag */: + return true; + case 148 /* Constructor */: + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return hasSomeImportantChild(item); + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 226 /* ModuleBlock */: + case 256 /* SourceFile */: + case 147 /* MethodDeclaration */: + case 148 /* Constructor */: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.forEach(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 218 /* VariableDeclaration */ && childKind !== 169 /* BindingElement */; + }); + } + } + } + // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. + var emptyChildItemArray = []; + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { return { - text: text, - kind: kind, - kindModifiers: kindModifiers, - spans: spans, - childItems: childItems, - indent: indent, + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, bolded: false, grayed: false }; } - function createTopLevelItem(node) { - switch (node.kind) { - case 256 /* SourceFile */: - return createSourceFileItem(node); - case 221 /* ClassDeclaration */: - return createClassItem(node); - case 147 /* MethodDeclaration */: - case 148 /* Constructor */: - return createMemberFunctionLikeItem(node); - case 224 /* EnumDeclaration */: - return createEnumItem(node); - case 222 /* InterfaceDeclaration */: - return createInterfaceItem(node); - case 225 /* ModuleDeclaration */: - return createModuleItem(node); - case 220 /* FunctionDeclaration */: - return createFunctionItem(node); - case 223 /* TypeAliasDeclaration */: - return createTypeAliasItem(node); - } - return undefined; - function createModuleItem(node) { - var moduleName = getModuleName(node); - var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem); - return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createFunctionItem(node) { - if (node.body && node.body.kind === 199 /* Block */) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return undefined; } - function createTypeAliasItem(node) { - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.typeElement, ts.getNodeModifiers(node), [getNodeSpan(node)], [], getIndent(node)); - } - function createMemberFunctionLikeItem(node) { - if (node.body && node.body.kind === 199 /* Block */) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - var scriptElementKind = void 0; - var memberFunctionName = void 0; - if (node.kind === 147 /* MethodDeclaration */) { - memberFunctionName = ts.getPropertyNameForPropertyNameNode(node.name); - scriptElementKind = ts.ScriptElementKind.memberFunctionElement; - } - else { - memberFunctionName = "constructor"; - scriptElementKind = ts.ScriptElementKind.constructorImplementationElement; - } - return getNavigationBarItem(memberFunctionName, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - return undefined; - } - function createSourceFileItem(node) { - var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); - var rootName = ts.isExternalModule(node) - ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\"" - : ""; - return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems); - } - function createClassItem(node) { - var childItems; - if (node.members) { - var constructor = ts.forEach(node.members, function (member) { - return member.kind === 148 /* Constructor */ && member; - }); - // Add the constructor parameters in as children of the class (for property parameters). - // Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that - // are not properties will be filtered out later by createChildItem. - var nodes = removeDynamicallyNamedProperties(node); - if (constructor) { - ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); })); - } - childItems = getItemsWorker(sortNodes(nodes), createChildItem); - } - var nodeName = !node.name ? "default" : node.name.text; - return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createEnumItem(node) { - var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createInterfaceItem(node) { - var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - } - function getModuleName(moduleDeclaration) { - // We want to maintain quotation marks. - if (ts.isAmbientModule(moduleDeclaration)) { - return getTextOfNode(moduleDeclaration.name); - } - // Otherwise, we need to aggregate each identifier to build up the qualified name. - var result = []; - result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { - moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); - } - return result.join("."); - } - function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 140 /* ComputedPropertyName */; }); - } - /** - * Like removeComputedProperties, but retains the properties with well known symbol names - */ - function removeDynamicallyNamedProperties(node) { - return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); - } - function getInnermostModule(node) { - while (node.body.kind === 225 /* ModuleDeclaration */) { - node = node.body; - } - return node; - } - function getNodeSpan(node) { - return node.kind === 256 /* SourceFile */ - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getTextOfNode(node) { - return ts.getTextOfNodeFromSourceText(sourceFile.text, node); + return spans; } } - NavigationBar.getNavigationBarItems = getNavigationBarItems; - function getJsNavigationBarItems(sourceFile, compilerOptions) { - var anonFnText = ""; - var anonClassText = ""; - var indent = 0; - var rootName = ts.isExternalModule(sourceFile) ? - "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" - : ""; - var sourceFileItem = getNavBarItem(rootName, ts.ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]); - var topItem = sourceFileItem; - // Walk the whole file, because we want to also find function expressions - which may be in variable initializer, - // call arguments, expressions, etc... - ts.forEachChild(sourceFile, visitNode); - function visitNode(node) { - var newItem = createNavBarItem(node); - if (newItem) { - topItem.childItems.push(newItem); - } - if (node.jsDocComments && node.jsDocComments.length > 0) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - visitNode(jsDocComment); - } - } - // Add a level if traversing into a container - if (newItem && (ts.isFunctionLike(node) || ts.isClassLike(node))) { - var lastTop = topItem; - indent++; - topItem = newItem; - ts.forEachChild(node, visitNode); - topItem = lastTop; - indent--; - // If the last item added was an anonymous function expression, and it had no children, discard it. - if (newItem && newItem.text === anonFnText && newItem.childItems.length === 0) { - topItem.childItems.pop(); - } - } - else { - ts.forEachChild(node, visitNode); - } - } - function createNavBarItem(node) { - switch (node.kind) { - case 218 /* VariableDeclaration */: - // Only add to the navbar if at the top-level of the file - // Note: "const" and "let" are also SyntaxKind.VariableDeclarations - if (node.parent /*VariableDeclarationList*/.parent /*VariableStatement*/ - .parent /*SourceFile*/.kind !== 256 /* SourceFile */) { - return undefined; + // TODO: GH#9145: We should just use getNodeKind. No reason why navigationBar and navigateTo should have different behaviors. + function nodeKind(node) { + switch (node.kind) { + case 256 /* SourceFile */: + return ts.ScriptElementKind.moduleElement; + case 255 /* EnumMember */: + return ts.ScriptElementKind.memberVariableElement; + case 218 /* VariableDeclaration */: + case 169 /* BindingElement */: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169 /* BindingElement */) { + name_38 = node.name; + variableDeclarationNode = node; + // binding elements are added only for variable declarations + // bubble up to the containing variable declaration + while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { + variableDeclarationNode = variableDeclarationNode.parent; } - // If it is initialized with a function expression, handle it when we reach the function expression node - var varDecl = node; - if (varDecl.initializer && (varDecl.initializer.kind === 179 /* FunctionExpression */ || - varDecl.initializer.kind === 180 /* ArrowFunction */ || - varDecl.initializer.kind === 192 /* ClassExpression */)) { - return undefined; - } - // Fall through - case 220 /* FunctionDeclaration */: - case 221 /* ClassDeclaration */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - // "export default function().." looks just like a regular function/class declaration, except with the 'default' flag - var name_37 = node.flags && (node.flags & 512 /* Default */) && !node.name ? "default" : - node.kind === 148 /* Constructor */ ? "constructor" : - ts.declarationNameToString(node.name); - return getNavBarItem(name_37, getScriptKindForElementKind(node.kind), [getNodeSpan(node)]); - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 192 /* ClassExpression */: - return getDefineModuleItem(node) || getFunctionOrClassExpressionItem(node); - case 147 /* MethodDeclaration */: - var methodDecl = node; - return getNavBarItem(ts.declarationNameToString(methodDecl.name), ts.ScriptElementKind.memberFunctionElement, [getNodeSpan(node)]); - case 235 /* ExportAssignment */: - // e.g. "export default " - return getNavBarItem("default", ts.ScriptElementKind.variableElement, [getNodeSpan(node)]); - case 231 /* ImportClause */: - if (!node.name) { - // No default import (this node is still a parent of named & namespace imports, which are handled below) - return undefined; - } - // fall through - case 234 /* ImportSpecifier */: // e.g. 'id' in: import {id} from 'mod' (in NamedImports, in ImportClause) - case 232 /* NamespaceImport */: // e.g. '* as ns' in: import * as ns from 'mod' (in ImportClause) - case 238 /* ExportSpecifier */: - // Export specifiers are only interesting if they are reexports from another module, or renamed, else they are already globals - if (node.kind === 238 /* ExportSpecifier */) { - if (!node.parent.parent.moduleSpecifier && !node.propertyName) { - return undefined; - } - } - var decl = node; - if (!decl.name) { - return undefined; - } - var declName = ts.declarationNameToString(decl.name); - return getNavBarItem(declName, ts.ScriptElementKind.constElement, [getNodeSpan(node)]); - case 279 /* JSDocTypedefTag */: - if (node.name) { - return getNavBarItem(node.name.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69 /* Identifier */) { - return getNavBarItem(nameIdentifier.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - } - } - } - default: - return undefined; - } - } - function getNavBarItem(text, kind, spans, kindModifiers) { - if (kindModifiers === void 0) { kindModifiers = ts.ScriptElementKindModifier.none; } - return { - text: text, kind: kind, kindModifiers: kindModifiers, spans: spans, childItems: [], indent: indent, bolded: false, grayed: false - }; - } - function getDefineModuleItem(node) { - if (node.kind !== 179 /* FunctionExpression */ && node.kind !== 180 /* ArrowFunction */) { - return undefined; - } - // No match if this is not a call expression to an identifier named 'define' - if (node.parent.kind !== 174 /* CallExpression */) { - return undefined; - } - var callExpr = node.parent; - if (callExpr.expression.kind !== 69 /* Identifier */ || callExpr.expression.getText() !== "define") { - return undefined; - } - // Return a module of either the given text in the first argument, or of the source file path - var defaultName = node.getSourceFile().fileName; - if (callExpr.arguments[0].kind === 9 /* StringLiteral */) { - defaultName = (callExpr.arguments[0]).text; - } - return getNavBarItem(defaultName, ts.ScriptElementKind.moduleElement, [getNodeSpan(node.parent)]); - } - function getFunctionOrClassExpressionItem(node) { - if (node.kind !== 179 /* FunctionExpression */ && - node.kind !== 180 /* ArrowFunction */ && - node.kind !== 192 /* ClassExpression */) { - return undefined; - } - var fnExpr = node; - var fnName; - if (fnExpr.name && ts.getFullWidth(fnExpr.name) > 0) { - // The expression has an identifier, so use that as the name - fnName = ts.declarationNameToString(fnExpr.name); - } - else { - // See if it is a var initializer. If so, use the var name. - if (fnExpr.parent.kind === 218 /* VariableDeclaration */) { - fnName = ts.declarationNameToString(fnExpr.parent.name); - } - else if (fnExpr.parent.kind === 187 /* BinaryExpression */ && - fnExpr.parent.operatorToken.kind === 56 /* EqualsToken */) { - fnName = fnExpr.parent.left.getText(); - } - else if (fnExpr.parent.kind === 253 /* PropertyAssignment */ && - fnExpr.parent.name) { - fnName = fnExpr.parent.name.getText(); + ts.Debug.assert(!!variableDeclarationNode); } else { - fnName = node.kind === 192 /* ClassExpression */ ? anonClassText : anonFnText; + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; } - } - var scriptKind = node.kind === 192 /* ClassExpression */ ? ts.ScriptElementKind.classElement : ts.ScriptElementKind.functionElement; - return getNavBarItem(fnName, scriptKind, [getNodeSpan(node)]); - } - function getNodeSpan(node) { - return node.kind === 256 /* SourceFile */ - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getScriptKindForElementKind(kind) { - switch (kind) { - case 218 /* VariableDeclaration */: + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { return ts.ScriptElementKind.variableElement; - case 220 /* FunctionDeclaration */: - return ts.ScriptElementKind.functionElement; - case 221 /* ClassDeclaration */: - return ts.ScriptElementKind.classElement; - case 148 /* Constructor */: - return ts.ScriptElementKind.constructorImplementationElement; - case 149 /* GetAccessor */: - return ts.ScriptElementKind.memberGetAccessorElement; - case 150 /* SetAccessor */: - return ts.ScriptElementKind.memberSetAccessorElement; - default: - return "unknown"; - } + } + case 180 /* ArrowFunction */: + return ts.ScriptElementKind.functionElement; + case 279 /* JSDocTypedefTag */: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); } - return sourceFileItem.childItems; } - NavigationBar.getJsNavigationBarItems = getJsNavigationBarItems; + function getModuleName(moduleDeclaration) { + // We want to maintain quotation marks. + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + // Otherwise, we need to aggregate each identifier to build up the qualified name. + var result = []; + result.push(moduleDeclaration.name.text); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + moduleDeclaration = moduleDeclaration.body; + result.push(moduleDeclaration.name.text); + } + return result.join("."); + } + /** + * For 'module A.B.C', we want to get the node for 'C'. + * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. + */ + function getInteriorModule(decl) { + return decl.body.kind === 225 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 140 /* ComputedPropertyName */; + } + function getNodeSpan(node) { + return node.kind === 256 /* SourceFile */ + ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) + : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); + } + function getFunctionOrClassName(node) { + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + else if (node.parent.kind === 218 /* VariableDeclaration */) { + return ts.declarationNameToString(node.parent.name); + } + else if (node.parent.kind === 187 /* BinaryExpression */ && + node.parent.operatorToken.kind === 56 /* EqualsToken */) { + return nodeText(node.parent.left); + } + else if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.name) { + return nodeText(node.parent.name); + } + else if (node.flags & 512 /* Default */) { + return "default"; + } + else { + return ts.isClassLike(node) ? "" : ""; + } + } + function isFunctionOrClassExpression(node) { + return node.kind === 179 /* FunctionExpression */ || node.kind === 180 /* ArrowFunction */ || node.kind === 192 /* ClassExpression */; + } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); /* @internal */ @@ -47848,9 +48643,9 @@ var ts; } getTypingNamesFromSourceFileNames(fileNames); // Add the cached typing locations for inferred typings that are already installed - for (var name_38 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_38) && !inferredTypings[name_38]) { - inferredTypings[name_38] = packageNameToTypingLocation[name_38]; + for (var name_39 in packageNameToTypingLocation) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } // Remove typings that the user has added to the exclude list @@ -47936,9 +48731,9 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, "*.json", /*exclude*/ undefined, /*depth*/ 2); - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); if (ts.getBaseFileName(normalizedFileName) !== "package.json") { continue; @@ -48679,9 +49474,9 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_39 in o) { - if (o[name_39] === rule) { - return name_39; + for (var name_40 in o) { + if (o[name_40] === rule) { + return name_40; } } throw new Error("Unknown rule"); @@ -50686,6 +51481,7 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// +/// /// /// /// @@ -50825,8 +51621,8 @@ var ts; var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -50961,7 +51757,7 @@ var ts; addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); } // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 225 /* ModuleDeclaration */ && declaration.body.kind === 225 /* ModuleDeclaration */) { + if (declaration.kind === 225 /* ModuleDeclaration */ && declaration.body && declaration.body.kind === 225 /* ModuleDeclaration */) { return; } if ((declaration.kind === 179 /* FunctionExpression */ || declaration.kind === 180 /* ArrowFunction */) && @@ -51797,11 +52593,11 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptions_stringToEnum; + var commandLineOptionsStringToEnum; /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ function fixupCompilerOptions(options, diagnostics) { // Lazily create this value to fix module loading errors. - commandLineOptions_stringToEnum = commandLineOptions_stringToEnum || ts.filter(ts.optionDeclarations, function (o) { + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); @@ -51822,8 +52618,8 @@ var ts; } } }; - for (var _i = 0, commandLineOptions_stringToEnum_1 = commandLineOptions_stringToEnum; _i < commandLineOptions_stringToEnum_1.length; _i++) { - var opt = commandLineOptions_stringToEnum_1[_i]; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; _loop_2(opt); } return options; @@ -51848,6 +52644,17 @@ var ts; // We are not returning a sourceFile for lib file when asked by the program, // so pass --noLib to avoid reporting a file not found error. options.noLib = true; + // Clear out other settings that would not be used in transpiling this module + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; // We are not doing a full typecheck, we are not resolving the whole context, // so pass --noResolve to avoid reporting missing file errors. options.noResolve = true; @@ -51882,7 +52689,8 @@ var ts; getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; } + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -51970,7 +52778,7 @@ var ts; var buckets = {}; var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + settings.typesRoot + "|" + settings.typesSearchPaths + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); + return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = ts.lookUp(buckets, key); @@ -52716,7 +53524,8 @@ var ts; oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs); + oldSettings.allowJs !== newSettings.allowJs || + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -52739,8 +53548,10 @@ var ts; return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); }, directoryExists: function (directoryName) { - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; } }; if (host.trace) { @@ -53588,8 +54399,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_40 = element.propertyName || element.name; - existingImportsOrExports[name_40.text] = true; + var name_41 = element.propertyName || element.name; + existingImportsOrExports[name_41.text] = true; } if (ts.isEmpty(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -53709,14 +54520,14 @@ var ts; var entries = []; var target = program.getCompilerOptions().target; var nameTable = getNameTable(sourceFile); - for (var name_41 in nameTable) { + for (var name_42 in nameTable) { // Skip identifiers produced only from the current location - if (nameTable[name_41] === position) { + if (nameTable[name_42] === position) { continue; } - if (!uniqueNames[name_41]) { - uniqueNames[name_41] = name_41; - var displayName = getCompletionEntryDisplayName(name_41, target, /*performCharacterChecks*/ true); + if (!uniqueNames[name_42]) { + uniqueNames[name_42] = name_42; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, /*performCharacterChecks*/ true); if (displayName) { var entry = { name: displayName, @@ -53833,10 +54644,10 @@ var ts; var typeChecker = program.getTypeChecker(); var type = typeChecker.getContextualType(node); if (type) { - var entries_1 = []; - addStringLiteralCompletionsFromType(type, entries_1); - if (entries_1.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_1 }; + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -55136,7 +55947,8 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference + isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isDefinition: false }); } } @@ -55486,7 +56298,8 @@ var ts; references: [{ fileName: sourceFile.fileName, textSpan: ts.createTextSpan(position, searchText.length), - isWriteAccess: false + isWriteAccess: false, + isDefinition: false }] }); } @@ -55964,7 +56777,8 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node) + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) }; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ @@ -56206,7 +57020,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); + return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -56639,7 +57453,8 @@ var ts; return; case 142 /* Parameter */: if (token.parent.name === token) { - return 17 /* parameterName */; + var isThis = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; + return isThis ? 3 /* keyword */ : 17 /* parameterName */; } return; } @@ -58437,6 +59252,7 @@ var ts; function CoreServicesShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } @@ -58444,17 +59260,26 @@ var ts; this.realpath = function (path) { return _this.shimHost.realpath(path); }; } } - CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude, depth) { + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { // Wrap the API changes for 2.0 release. This try/catch // should be removed once TypeScript 2.0 has shipped. - var encoded; try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude), depth); + var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); } catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); + var results = []; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { + var file = _b[_a]; + if (!ts.contains(results, file)) { + results.push(file); + } + } + } + return results; } - return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -58462,6 +59287,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; + CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { + return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -58987,4 +59815,4 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = "1.9"; -/* tslint:enable:no-unused-variable */ +/* tslint:enable:no-unused-variable */ diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index a9930066fc1..76690ff9d0f 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -713,7 +713,6 @@ declare namespace ts { } interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; - dotToken: Node; name: Identifier; } type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression; @@ -844,6 +843,7 @@ declare namespace ts { interface SwitchStatement extends Statement { expression: Expression; caseBlock: CaseBlock; + possiblyExhaustive?: boolean; } interface CaseBlock extends Node { clauses: NodeArray; @@ -919,7 +919,7 @@ declare namespace ts { type ModuleBody = ModuleBlock | ModuleDeclaration; interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; - body: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | ModuleDeclaration; } interface ModuleBlock extends Node, Statement { statements: NodeArray; @@ -1075,8 +1075,9 @@ declare namespace ts { Assignment = 16, TrueCondition = 32, FalseCondition = 64, - Referenced = 128, - Shared = 256, + SwitchClause = 128, + Referenced = 256, + Shared = 512, Label = 12, Condition = 96, } @@ -1098,6 +1099,12 @@ declare namespace ts { expression: Expression; antecedent: FlowNode; } + interface FlowSwitchClause extends FlowNode { + switchStatement: SwitchStatement; + clauseStart: number; + clauseEnd: number; + antecedent: FlowNode; + } interface AmdDependency { path: string; name: string; @@ -1132,7 +1139,13 @@ declare namespace ts { getCurrentDirectory(): string; } interface ParseConfigHost { - readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; + useCaseSensitiveFileNames: boolean; + readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[]; + /** + * Gets a value indicating whether the specified path exists and is a file. + * @param path The path to test. + */ + fileExists(path: string): boolean; } interface WriteFileCallback { (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; @@ -1412,7 +1425,6 @@ declare namespace ts { ThisType = 33554432, ObjectLiteralPatternWithComputedProperties = 67108864, Never = 134217728, - Falsy = 126, StringLike = 258, NumberLike = 132, ObjectType = 80896, @@ -1574,7 +1586,10 @@ declare namespace ts { suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; traceResolution?: boolean; + disableSizeLimit?: boolean; types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; typesSearchPaths?: string[]; [option: string]: CompilerOptionsValue | undefined; } @@ -1638,6 +1653,15 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; + wildcardDirectories?: Map; + } + enum WatchDirectoryFlags { + None = 0, + Recursive = 1, + } + interface ExpandResult { + fileNames: string[]; + wildcardDirectories: Map; } interface ModuleResolutionHost { fileExists(fileName: string): boolean; @@ -1672,6 +1696,7 @@ declare namespace ts { getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; + getDirectories(path: string): string[]; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; @@ -1707,6 +1732,7 @@ declare namespace ts { useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string; + getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; @@ -1717,7 +1743,7 @@ declare namespace ts { getExecutingFilePath(): string; getCurrentDirectory(): string; getDirectories(path: string): string[]; - readDirectory(path: string, extension?: string, exclude?: string[]): string[]; + readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; getModifiedTime?(path: string): Date; createHash?(data: string): string; getMemoryUsage?(): number; @@ -1821,6 +1847,7 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { + /** The version of the TypeScript compiler release */ const version: string; function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; @@ -1836,7 +1863,15 @@ declare namespace ts { function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function getDefaultTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; + /** + * Given a set of options and a set of root files, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -1978,6 +2013,7 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; + getDirectories?(directoryName: string): string[]; } interface LanguageService { cleanupSemanticCache(): void; @@ -2068,6 +2104,7 @@ declare namespace ts { textSpan: TextSpan; fileName: string; isWriteAccess: boolean; + isDefinition: boolean; } interface DocumentHighlights { fileName: string; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 9e41f640305..30d49888df1 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -439,8 +439,9 @@ var ts; FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; - FlowFlags[FlowFlags["Referenced"] = 128] = "Referenced"; - FlowFlags[FlowFlags["Shared"] = 256] = "Shared"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["Referenced"] = 256] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 512] = "Shared"; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; })(ts.FlowFlags || (ts.FlowFlags = {})); @@ -654,7 +655,8 @@ var ts; TypeFlags[TypeFlags["Never"] = 134217728] = "Never"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 96] = "Nullable"; - TypeFlags[TypeFlags["Falsy"] = 126] = "Falsy"; + /* @internal */ + TypeFlags[TypeFlags["Falsy"] = 112] = "Falsy"; /* @internal */ TypeFlags[TypeFlags["Intrinsic"] = 150995071] = "Intrinsic"; /* @internal */ @@ -755,6 +757,11 @@ var ts; DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; })(ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); var DiagnosticStyle = ts.DiagnosticStyle; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + var WatchDirectoryFlags = ts.WatchDirectoryFlags; /* @internal */ (function (CharacterCodes) { CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; @@ -994,6 +1001,15 @@ var ts; return -1; } ts.indexOf = indexOf; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0, len = text.length; i < len; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; function countWhere(array, predicate) { var count = 0; if (array) { @@ -1021,12 +1037,24 @@ var ts; return result; } ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + if (f(item)) { + array[outIndex] = item; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; function map(array, f) { var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result.push(f(v)); } } @@ -1045,8 +1073,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; if (!contains(result, item, areEqual)) { result.push(item); } @@ -1057,8 +1085,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var v = array_7[_i]; result += v[prop]; } return result; @@ -1383,6 +1411,30 @@ var ts; return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; } ts.compareValues = compareValues; + function compareStrings(a, b, ignoreCase) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + if (ignoreCase) { + if (String.prototype.localeCompare) { + var result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); + return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + a = a.toUpperCase(); + b = b.toUpperCase(); + if (a === b) + return 0 /* EqualTo */; + } + return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + ts.compareStrings = compareStrings; + function compareStringsCaseInsensitive(a, b) { + return compareStrings(a, b, /*ignoreCase*/ true); + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } @@ -1637,12 +1689,242 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; + /** + * Removes a trailing directory separator from a path. + * @param path The path. + */ + function removeTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) === ts.directorySeparator) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + /** + * Adds a trailing directory separator to a path, if it does not already have one. + * @param path The path. + */ + function ensureTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) !== ts.directorySeparator) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + a = removeTrailingDirectorySeparator(a); + b = removeTrailingDirectorySeparator(b); + var aComponents = getNormalizedPathComponents(a, currentDirectory); + var bComponents = getNormalizedPathComponents(b, currentDirectory); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + if (result !== 0 /* EqualTo */) { + return result; + } + } + return compareValues(aComponents.length, bComponents.length); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + parent = removeTrailingDirectorySeparator(parent); + child = removeTrailingDirectorySeparator(child); + if (parent === child) + return true; + var parentComponents = getNormalizedPathComponents(parent, currentDirectory); + var childComponents = getNormalizedPathComponents(child, currentDirectory); + if (childComponents.length < parentComponents.length) { + return false; + } + for (var i = 0; i < parentComponents.length; i++) { + var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); + if (result !== 0 /* EqualTo */) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; function fileExtensionIs(path, extension) { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsAny(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsAny = fileExtensionIsAny; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + function getRegularExpressionForWildcard(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + var pattern = ""; + var hasWrittenSubpattern = false; + spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + var spec = specs_1[_i]; + if (!spec) { + continue; + } + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + if (usage !== "exclude" && components[components.length - 1] === "**") { + continue spec; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + var optionalCount = 0; + for (var _a = 0, components_1 = components; _a < components_1.length; _a++) { + var component = components_1[_a]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + continue spec; + } + subpattern += "(/.+?)?"; + hasRecursiveDirectoryWildcard = true; + hasWrittenComponent = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + hasWrittenComponent = true; + } + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + if (hasWrittenSubpattern) { + pattern += "|"; + } + pattern += "(" + subpattern + ")"; + hasWrittenSubpattern = true; + } + if (!pattern) { + return undefined; + } + return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + } + function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var regexFlag = useCaseSensitiveFileNames ? "" : "i"; + var includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag); + var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); + var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var result = []; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + } + return result; + function visitDirectory(path, absolutePath) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; + var name_1 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!extensions || fileExtensionIsAny(name_1, extensions)) && + (!includeFileRegex || includeFileRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + result.push(name_1); + } + } + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var current = directories_1[_b]; + var name_2 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name_2, absoluteName); + } + } + } + } + ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). + var basePaths = [path]; + if (includes) { + // Storage for literal base paths amongst the include patterns. + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + if (isRootedDiskPath(include)) { + var wildcardOffset = indexOfAnyCharCode(include, wildcardCharCodes); + var includeBasePath = wildcardOffset < 0 + ? removeTrailingDirectorySeparator(getDirectoryPath(include)) + : include.substring(0, include.lastIndexOf(ts.directorySeparator, wildcardOffset)); + // Append the literal and canonical candidate base paths. + includeBasePaths.push(includeBasePath); + } + } + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path + include: for (var i = 0; i < includeBasePaths.length; i++) { + var includeBasePath = includeBasePaths[i]; + for (var j = 0; j < basePaths.length; j++) { + if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { + continue include; + } + } + basePaths.push(includeBasePath); + } + } + return basePaths; + } function ensureScriptKind(fileName, scriptKind) { // Using scriptKind as a condition handles both: // - 'scriptKind' is unspecified and thus it is `undefined` @@ -1692,6 +1974,57 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Limit"] = 5] = "Limit"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ts.ExtensionPriority || (ts.ExtensionPriority = {})); + var ExtensionPriority = ts.ExtensionPriority; + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i); + } + } + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; + } + ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ + function adjustExtensionPriority(extensionPriority) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; + } + else if (extensionPriority < 5 /* Limit */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return 5 /* Limit */; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ + function getNextLowestExtensionPriority(extensionPriority) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return 5 /* Limit */; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { @@ -1712,6 +2045,10 @@ var ts; return ext === ".jsx" || ext === ".tsx"; } ts.isJsxOrTsxExtension = isJsxOrTsxExtension; + function changeExtension(path, newExtension) { + return (removeFileExtension(path) + newExtension); + } + ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -1790,6 +2127,7 @@ var ts; ts.sys = (function () { function getWScriptSystem() { var fso = new ActiveXObject("Scripting.FileSystemObject"); + var shell = new ActiveXObject("WScript.Shell"); var fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2 /*text*/; var binaryStream = new ActiveXObject("ADODB.Stream"); @@ -1851,9 +2189,6 @@ var ts; fileStream.Close(); } } - function getCanonicalPath(path) { - return path.toLowerCase(); - } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -1865,30 +2200,19 @@ var ts; var folder = fso.GetFolder(path); return getNames(folder.subfolders); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { + function getAccessibleFileSystemEntries(path) { + try { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; - var name_1 = ts.combinePaths(path, current); - if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { - result.push(name_1); - } - } - var subfolders = getNames(folder.subfolders); - for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { - var current = subfolders_1[_a]; - var name_2 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_2))) { - visitDirectory(name_2); - } - } + var directories = getNames(folder.subfolders); + return { files: files, directories: directories }; } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } return { args: args, @@ -1917,7 +2241,7 @@ var ts; return WScript.ScriptFullName; }, getCurrentDirectory: function () { - return new ActiveXObject("WScript.Shell").CurrentDirectory; + return shell.CurrentDirectory; }, getDirectories: getDirectories, readDirectory: readDirectory, @@ -2056,8 +2380,41 @@ var ts; } } } - function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path : path.toLowerCase(); + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var entry = entries_1[_i]; + // This is necessary because on some file system node fails to exclude + // "." and "..". See https://github.com/nodejs/node/issues/4002 + if (entry === "." || entry === "..") { + continue; + } + var name_3 = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name_3); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } var FileSystemEntryKind; (function (FileSystemEntryKind) { @@ -2085,40 +2442,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); }); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { - var files = _fs.readdirSync(path || ".").sort(); - var directories = []; - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var current = files_2[_i]; - // This is necessary because on some file system node fails to exclude - // "." and "..". See https://github.com/nodejs/node/issues/4002 - if (current === "." || current === "..") { - continue; - } - var name_3 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_3))) { - var stat = _fs.statSync(name_3); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name_3, extension)) { - result.push(name_3); - } - } - else if (stat.isDirectory()) { - directories.push(name_3); - } - } - } - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var current = directories_1[_a]; - visitDirectory(current); - } - } - } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -2206,6 +2529,16 @@ var ts; } return process.memoryUsage().heapUsed; }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (e) { } + return 0; + }, exit: function (exitCode) { process.exit(exitCode); }, @@ -2239,7 +2572,10 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - readDirectory: ChakraHost.readDirectory, + readDirectory: function (path, extensions, excludes, includes) { + var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, exit: ChakraHost.quit, realpath: realpath }; @@ -2409,7 +2745,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_a_binding_pattern_1187", message: "A parameter property may not be a binding pattern." }, + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, @@ -2425,7 +2761,6 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower_1204", message: "Cannot compile modules into 'es2015' when targeting 'ES5' or lower." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -2480,6 +2815,7 @@ var ts; Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -2750,6 +3086,8 @@ var ts; The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, + Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, + Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2823,6 +3161,8 @@ var ts; Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." }, Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, @@ -2996,7 +3336,6 @@ var ts; types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "property_declarations_can_only_be_used_in_a_ts_file_8014", message: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, @@ -4985,6 +5324,11 @@ var ts; (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModule(node) { + // The only kind of module that can be missing a body is a shorthand ambient module. + return node.kind === 225 /* ModuleDeclaration */ && (!node.body); + } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 /* SourceFile */ || node.kind === 225 /* ModuleDeclaration */ || @@ -5417,6 +5761,7 @@ var ts; case 157 /* ConstructorType */: return true; } + return false; } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { @@ -5839,6 +6184,18 @@ var ts; return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + /** + * Returns true if the node is a variable declaration whose initializer is a function expression. + * This function does not test if the node is in a JavaScript file or not. + */ + function isDeclarationOfFunctionExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 218 /* VariableDeclaration */) { + var declaration = s.valueDeclaration; + return declaration.initializer && declaration.initializer.kind === 179 /* FunctionExpression */; + } + return false; + } + ts.isDeclarationOfFunctionExpression = isDeclarationOfFunctionExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder function getSpecialPropertyAssignmentKind(expression) { @@ -6815,7 +7172,9 @@ var ts; ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; @@ -7175,6 +7534,10 @@ var ts; return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -7679,7 +8042,6 @@ var ts; return visitNodes(cbNodes, node.properties); case 172 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); case 173 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || @@ -8602,6 +8964,7 @@ var ts; return token === 19 /* OpenBracketToken */ || token === 15 /* OpenBraceToken */ || token === 37 /* AsteriskToken */ + || token === 22 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenIsClassOrFunction() { @@ -10703,7 +11066,7 @@ var ts; // If it wasn't then just try to parse out a '.' and report an error. var node = createNode(172 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - node.dotToken = parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } @@ -10905,7 +11268,6 @@ var ts; if (dotToken) { var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; - propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; @@ -12250,7 +12612,12 @@ var ts; else { node.name = parseLiteralNode(/*internName*/ true); } - node.body = parseModuleBlock(); + if (token === 15 /* OpenBraceToken */) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { @@ -13341,8 +13708,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -13479,8 +13846,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -13752,7 +14119,8 @@ var ts; return state_1; } else if (node.kind === 225 /* ModuleDeclaration */) { - return getModuleInstanceState(node.body); + var body = node.body; + return body ? getModuleInstanceState(body) : 1 /* Instantiated */; } else { return 1 /* Instantiated */; @@ -14232,11 +14600,6 @@ var ts; break; } } - function isNarrowableReference(expr) { - return expr.kind === 69 /* Identifier */ || - expr.kind === 97 /* ThisKeyword */ || - expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); - } function isNarrowingExpression(expr) { switch (expr.kind) { case 69 /* Identifier */: @@ -14244,7 +14607,7 @@ var ts; case 172 /* PropertyAccessExpression */: return isNarrowableReference(expr); case 174 /* CallExpression */: - return true; + return hasNarrowableArgument(expr); case 178 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); case 187 /* BinaryExpression */: @@ -14254,6 +14617,35 @@ var ts; } return false; } + function isNarrowableReference(expr) { + return expr.kind === 69 /* Identifier */ || + expr.kind === 97 /* ThisKeyword */ || + expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 172 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 /* NullKeyword */ || expr1.kind === 69 /* Identifier */ && expr1.text === "undefined") && isNarrowableOperand(expr2); + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 182 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56 /* EqualsToken */: @@ -14262,20 +14654,34 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - if (isNarrowingExpression(expr.left) && (expr.right.kind === 93 /* NullKeyword */ || expr.right.kind === 69 /* Identifier */)) { - return true; - } - if (expr.left.kind === 182 /* TypeOfExpression */ && isNarrowingExpression(expr.left.expression) && expr.right.kind === 9 /* StringLiteral */) { - return true; - } - return false; + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91 /* InstanceOfKeyword */: - return isNarrowingExpression(expr.left); + return isNarrowableOperand(expr.left); case 24 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 178 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 187 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 56 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 24 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4 /* BranchLabel */, @@ -14290,7 +14696,7 @@ var ts; } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & 128 /* Referenced */ ? 256 /* Shared */ : 128 /* Referenced */; + flow.flags |= flow.flags & 256 /* Referenced */ ? 512 /* Shared */ : 256 /* Referenced */; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { @@ -14315,8 +14721,21 @@ var ts; setFlowNodeReferenced(antecedent); return { flags: flags, - antecedent: antecedent, - expression: expression + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingSwitchStatement(switchStatement)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128 /* SwitchClause */, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { @@ -14527,9 +14946,12 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasNonEmptyDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 /* DefaultClause */ && c.statements.length; }); - if (!hasNonEmptyDefault) { - addAntecedent(postSwitchLabel, preSwitchCaseFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); } currentBreakTarget = saveBreakTarget; preSwitchCaseFlow = savePreSwitchCaseFlow; @@ -14537,25 +14959,22 @@ var ts; } function bindCaseBlock(node) { var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { - var clause = clauses[i]; - if (clause.statements.length) { - if (currentFlow.flags & 1 /* Unreachable */) { - currentFlow = preSwitchCaseFlow; - } - else { - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, preSwitchCaseFlow); - addAntecedent(preCaseLabel, currentFlow); - currentFlow = finishFlowLabel(preCaseLabel); - } - bind(clause); - if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; } - else { - bind(clause); + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } } @@ -14855,7 +15274,7 @@ var ts; } function hasExportDeclarations(node) { var body = node.kind === 256 /* SourceFile */ ? node : node.body; - if (body.kind === 256 /* SourceFile */ || body.kind === 226 /* ModuleBlock */) { + if (body && (body.kind === 256 /* SourceFile */ || body.kind === 226 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; if (stat.kind === 236 /* ExportDeclaration */ || stat.kind === 235 /* ExportAssignment */) { @@ -15471,7 +15890,7 @@ var ts; constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; var funcSymbol = container.locals[constructorFunction.text]; - if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */)) { + if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return; } // Set up the members collection if it doesn't exist already @@ -16193,7 +16612,8 @@ var ts; var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if (modulekind || (!compilerOptions.outFile && !compilerOptions.out)) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out)) { // nodes are in different files and order cannot be determines return true; } @@ -16458,7 +16878,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -16532,6 +16953,29 @@ var ts; } return false; } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 /* Identifier */ || kind === 172 /* PropertyAccessExpression */) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194 /* ExpressionWithTypeArguments */) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0); // Block-scoped variables cannot be used before their definition @@ -16579,9 +17023,11 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = moduleSymbol.exports["export="] ? - getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : - resolveSymbol(moduleSymbol.exports["default"]); + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + moduleSymbol : + moduleSymbol.exports["export="] ? + getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : + resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -16650,6 +17096,9 @@ var ts; if (targetSymbol) { var name_10 = specifier.propertyName || specifier.name; if (name_10.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + return moduleSymbol; + } var symbolFromVariable = void 0; // First check if module was specified with "export=". If so, get the member from the resolved type if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { @@ -18171,6 +18620,9 @@ var ts; function isTypeAny(type) { return type && (type.flags & 1 /* Any */) !== 0; } + function isTypeNever(type) { + return type && (type.flags & 134217728 /* Never */) !== 0; + } // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. function getTypeForBindingElementParent(node) { @@ -18491,23 +18943,26 @@ var ts; if (declaration.kind === 235 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } - // Handle module.exports = expr - if (declaration.kind === 187 /* BinaryExpression */) { - return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - if (declaration.kind === 172 /* PropertyAccessExpression */) { - // Declarations only exist for property access expressions for certain - // special assignment kinds - if (declaration.parent.kind === 187 /* BinaryExpression */) { - // Handle exports.p = expr or this.p = expr or className.prototype.method = expr - return links.type = checkExpressionCached(declaration.parent.right); - } - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + var type = undefined; + // Handle module.exports = expr or this.p = expr + if (declaration.kind === 187 /* BinaryExpression */) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + else if (declaration.kind === 172 /* PropertyAccessExpression */) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === 187 /* BinaryExpression */) { + // Handle exports.p = expr or className.prototype.method = expr + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + } if (!popTypeResolution()) { if (symbol.valueDeclaration.type) { // Variable has type annotation that circularly references the variable itself @@ -18600,9 +19055,14 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var type = createObjectType(65536 /* Anonymous */, symbol); - links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? - addTypeKind(type, 32 /* Undefined */) : type; + if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + links.type = anyType; + } + else { + var type = createObjectType(65536 /* Anonymous */, symbol); + links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? + addTypeKind(type, 32 /* Undefined */) : type; + } } return links.type; } @@ -19660,7 +20120,7 @@ var ts; } return result; } - function isOptionalParameter(node) { + function isJSDocOptionalParameter(node) { if (node.flags & 134217728 /* JavaScriptFile */) { if (node.type && node.type.kind === 268 /* JSDocOptionalType */) { return true; @@ -19675,7 +20135,9 @@ var ts; } } } - if (ts.hasQuestionToken(node)) { + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -19734,7 +20196,7 @@ var ts; if (param.type && param.type.kind === 166 /* StringLiteralType */) { hasStringLiterals = true; } - if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { minArgumentCount = i - (hasThisParameter ? 1 : 0); } @@ -20818,6 +21280,9 @@ var ts; function isTypeComparableTo(source, target) { return checkTypeComparableTo(source, target, /*errorNode*/ undefined); } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } @@ -21897,8 +22362,10 @@ var ts; function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralType(type) { - return type.flags & 256 /* StringLiteral */; + function isStringLiteralUnionType(type) { + return type.flags & 256 /* StringLiteral */ ? true : + type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } /** * Check if a Type was written as a tuple type literal. @@ -22709,6 +23176,31 @@ var ts; } return node; } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 249 /* CaseClause */) { + var expr = clause.expression; + return expr.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + } + return undefined; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + // If all case clauses specify expressions that have unit types, we return an array + // of those unit types. Otherwise we return an empty array. + var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256 /* StringLiteral */; }) ? types : emptyArray; + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 16384 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function filterType(type, f) { + return type.flags & 16384 /* Union */ ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175 /* Narrowable */)) { @@ -22724,7 +23216,7 @@ var ts; return result; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 256 /* Shared */) { + if (flow.flags & 512 /* Shared */) { // We cache results of flow type resolution for shared nodes that were previously visited in // the same getFlowTypeOfReference invocation. A node is considered shared when it is the // antecedent of more than one node. @@ -22745,6 +23237,9 @@ var ts; else if (flow.flags & 96 /* Condition */) { type = getTypeAtFlowCondition(flow); } + else if (flow.flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } else if (flow.flags & 12 /* Label */) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; @@ -22769,7 +23264,7 @@ var ts; // simply return the declared type to reduce follow-on errors. type = declaredType; } - if (flow.flags & 256 /* Shared */) { + if (flow.flags & 512 /* Shared */) { // Record visited node and the associated type in the cache. visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; @@ -22825,6 +23320,10 @@ var ts; } return type; } + function getTypeAtSwitchClause(flow) { + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { @@ -22903,11 +23402,26 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - if (isNullOrUndefinedLiteral(expr.right)) { - return narrowTypeByNullCheck(type, expr, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (expr.left.kind === 182 /* TypeOfExpression */ && expr.right.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, expr, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + } + if (left.kind === 182 /* TypeOfExpression */ && right.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + } + if (right.kind === 182 /* TypeOfExpression */ && left.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + } + if (left.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + } + if (right.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91 /* InstanceOfKeyword */: @@ -22917,54 +23431,100 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, expr, assumeTrue) { - // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' on the right - var operator = expr.operatorToken.kind; + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' as value if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(expr.left))) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; var facts = doubleEquals ? assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - expr.right.kind === 93 /* NullKeyword */ ? + literal.kind === 93 /* NullKeyword */ ? assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - function narrowTypeByTypeof(type, expr, assumeTrue) { - // We have '==', '!=', '====', or !==' operator with 'typeof xxx' on the left - // and string literal on the right - var left = getReferenceFromExpression(expr.left.expression); - var right = expr.right; - if (!isMatchingReference(reference, left)) { + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands + var target = getReferenceFromExpression(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { + if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (expr.operatorToken.kind === 31 /* ExclamationEqualsToken */ || - expr.operatorToken.kind === 33 /* ExclamationEqualsEqualsToken */) { + if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } if (assumeTrue && !(type.flags & 16384 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primtive type. For example, type 'any' can be narrowed // to one of the primitive types. - var targetType = ts.getProperty(typeofTypesByName, right.text); + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, right.text) || 64 /* TypeofEQHostObject */ : - ts.getProperty(typeofNEFacts, right.text) || 8192 /* TypeofNEHostObject */; + ts.getProperty(typeofEQFacts, literal.text) || 64 /* TypeofEQHostObject */ : + ts.getProperty(typeofNEFacts, literal.text) || 8192 /* TypeofNEHostObject */; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with property access as target + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256 /* StringLiteral */) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We have switch statement with property access expression + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { @@ -23836,9 +24396,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } - function contextualTypeIsStringLiteralType(type) { - return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); - } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); @@ -24839,7 +25396,7 @@ var ts; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { - if (right.text) { + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 /* ThisType */ ? apparentType : type)); } return unknownType; @@ -26126,8 +26683,12 @@ var ts; // When resolved signature is a call signature (and not a construct signature) the result type is any, unless // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations // in a JS file - var funcSymbol = checkExpression(node.expression).symbol; - if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */)) { + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = node.expression.kind === 69 /* Identifier */ ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return getInferredClassType(funcSymbol); } else if (compilerOptions.noImplicitAny) { @@ -26147,6 +26708,7 @@ var ts; } function checkAssertion(node) { var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); @@ -26264,6 +26826,14 @@ var ts; } return emptyObjectType; } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { @@ -26297,19 +26867,12 @@ var ts; else { types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { - return neverType; + // For an async function, the return type will not be never, but rather a Promise for never. + return isAsync ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - if (isAsync) { - // For an async function, the return type will not be void, but rather a Promise for void. - var promiseType = createPromiseType(voidType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - return voidType; + // For an async function, the return type will not be void, but rather a Promise for void. + return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } // When yield/return statements are contextually typed we allow the return type to be a union type. @@ -26323,7 +26886,7 @@ var ts; else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience - return getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -26334,20 +26897,10 @@ var ts; reportErrorsFromWidening(func, type); } var widenedType = getWidenedType(type); - if (isAsync) { - // From within an async function you can return either a non-promise value or a promise. Any - // Promise/A+ compatible implementation will always assimilate any foreign promise, so the - // return type of the body is awaited type of the body, wrapped in a native Promise type. - var promiseType = createPromiseType(widenedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - else { - return widenedType; - } + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; @@ -26366,10 +26919,40 @@ var ts; }); return aggregatedTypes; } + function isExhaustiveSwitchStatement(node) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172 /* PropertyAccessExpression */) { + return false; + } + var type = checkExpression(expr.expression); + if (!(type.flags & 16384 /* Union */)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(propType, switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 32768 /* HasImplicitReturn */)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 213 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasReturnWithNoExpression = !!(func.flags & 32768 /* HasImplicitReturn */); + var hasReturnWithNoExpression = functionHasImplicitReturn(func); var hasReturnOfTypeNever = false; ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; @@ -26423,7 +27006,7 @@ var ts; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 /* Block */ || !(func.flags & 32768 /* HasImplicitReturn */)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 65536 /* HasExplicitReturn */; @@ -27016,7 +27599,7 @@ var ts; case 90 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); case 51 /* AmpersandAmpersandToken */: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 126 /* Falsy */) : rightType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112 /* Falsy */) : rightType; case 52 /* BarBarToken */: return getUnionType([getNonNullableType(leftType), rightType]); case 56 /* EqualsToken */: @@ -27132,7 +27715,7 @@ var ts; } function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + if (contextualType && isStringLiteralUnionType(contextualType)) { return getStringLiteralTypeForText(node.text); } return stringType; @@ -27979,9 +28562,6 @@ var ts; } } } - // when checking exported function declarations across modules check only duplicate implementations - // names and consistency of modifiers are verified when we check local symbol - var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536 /* Module */; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { @@ -28013,7 +28593,7 @@ var ts; duplicateFunctionDeclaration = true; } } - else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } if (ts.nodeIsPresent(node.body)) { @@ -28041,7 +28621,7 @@ var ts; }); } // Abstract methods can't have an implementation -- in particular, they don't need one. - if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !(lastSeenNonAmbientDeclaration.flags & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -28142,7 +28722,7 @@ var ts; } function checkNonThenableType(type, location, message) { type = getWidenedType(type); - if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) { if (location) { if (!message) { message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; @@ -28168,37 +28748,39 @@ var ts; // ): any; // } // - if (promise.flags & 1 /* Any */) { + if (isTypeAny(promise)) { return undefined; } - if ((promise.flags & 4096 /* Reference */) && promise.target === tryGetGlobalPromiseType()) { - return promise.typeArguments[0]; + if (promise.flags & 4096 /* Reference */) { + if (promise.target === tryGetGlobalPromiseType() + || promise.target === getGlobalPromiseLikeType()) { + return promise.typeArguments[0]; + } } var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (thenFunction && (thenFunction.flags & 1 /* Any */)) { + if (!thenFunction || isTypeAny(thenFunction)) { return undefined; } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray; + var thenSignatures = getSignaturesOfType(thenFunction, 0 /* Call */); if (thenSignatures.length === 0) { return undefined; } var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072 /* NEUndefined */); - if (onfulfilledParameterType.flags & 1 /* Any */) { + if (isTypeAny(onfulfilledParameterType)) { return undefined; } var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); - return valueParameterType; + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { - return getTypeAtPosition(signature, 0); + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; } /** * Gets the "awaited type" of a type. @@ -30189,7 +30771,7 @@ var ts; // - augmentation for a global scope is always applied // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Merged */); - if (checkBody) { + if (checkBody && node.body) { // body of ambient external module is always a module block for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; @@ -30217,7 +30799,13 @@ var ts; } } } - checkSourceElement(node.body); + if (compilerOptions.noImplicitAny && !node.body) { + // Ambient shorthand module is an implicit any + reportImplicitAnyError(node, anyType); + } + if (node.body) { + checkSourceElement(node.body); + } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { @@ -31982,7 +32570,10 @@ var ts; return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 142 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 142 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); @@ -33812,21 +34403,26 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body.kind !== 226 /* ModuleBlock */) { + while (node.body && node.body.kind !== 226 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; + if (node.body) { + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + else { + write(";"); + } } function writeTypeAliasDeclaration(node) { var prevEnclosingDeclaration = enclosingDeclaration; @@ -36393,7 +36989,6 @@ var ts; function createPropertyAccessExpression(expression, name) { var result = ts.createSynthesizedNode(172 /* PropertyAccessExpression */); result.expression = parenthesizeForAccess(expression); - result.dotToken = ts.createSynthesizedNode(21 /* DotToken */); result.name = name; return result; } @@ -36457,9 +37052,9 @@ var ts; emit(node.initializer); } // Return true if identifier resolves to an exported member of a namespace - function isNamespaceExportReference(node) { + function isExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 256 /* SourceFile */; + return !!container; } // Return true if identifier resolves to an imported identifier function isImportedReference(node) { @@ -36490,10 +37085,10 @@ var ts; // const foo_1 = require('./foo'); // exports.baz = { foo: foo_1.foo }; // - if (languageVersion < 2 /* ES6 */ || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isNamespaceExportReference(node.name)) { + if (languageVersion < 2 /* ES6 */ || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { // Emit identifier as an identifier write(": "); - emit(node.name); + emitExpressionIdentifier(node.name); } if (languageVersion >= 2 /* ES6 */ && node.objectAssignmentInitializer) { write(" = "); @@ -36552,7 +37147,10 @@ var ts; return; } emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; + var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; + var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); // 1 .toString is a valid property access, emit a space after the literal // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal var shouldEmitSpace = false; @@ -36575,7 +37173,7 @@ var ts; else { write("."); } - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -37014,7 +37612,6 @@ var ts; synthesizedLHS = ts.createSynthesizedNode(172 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; - synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; write(", "); } @@ -39556,7 +40153,11 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { + var isES6ExportedClass = isES6ExportedDeclaration(node); if (node.kind === 221 /* ClassDeclaration */) { + if (isES6ExportedClass && !(node.flags & 512 /* Default */)) { + write("export "); + } // source file level classes in system modules are hoisted so 'var's for them are already defined if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); @@ -39621,9 +40222,15 @@ var ts; write(";"); } emitEnd(node); - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 221 /* ClassDeclaration */ && !isES6ExportedClass) { emitExportMemberAssignment(node); } + else if (isES6ExportedClass && (node.flags & 512 /* Default */)) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); @@ -40000,10 +40607,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 160 /* ArrayType */) { + if (parameterType && parameterType.kind === 160 /* ArrayType */) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 155 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType && parameterType.kind === 155 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -40021,9 +40628,15 @@ var ts; } /** Serializes the return type of function. Used by the __metadata decorator for a method. */ function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node) && node.type) { - emitSerializedTypeNode(node.type); - return; + if (node && ts.isFunctionLike(node)) { + if (node.type) { + emitSerializedTypeNode(node.type); + return; + } + else if (ts.isAsyncFunctionLike(node)) { + write("Promise"); + return; + } } write("void 0"); } @@ -40162,7 +40775,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + if (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -40204,6 +40817,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); + ts.Debug.assert(node.body !== undefined); // node.body must exist, as this is a non-ambient module if (node.body.kind === 226 /* ModuleBlock */) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; @@ -41998,13 +42612,9 @@ var ts; /* @internal */ ts.ioReadTime = 0; /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ - var emptyArray = []; - var defaultLibrarySearchPaths = [ - "types/", - "node_modules/", - "node_modules/@types/", - ]; ts.version = "1.9.0"; + var emptyArray = []; + var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { while (true) { var fileName = ts.combinePaths(searchPath, "tsconfig.json"); @@ -42144,6 +42754,10 @@ var ts; return undefined; } var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + return options.typeRoots || + ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(), d); }); + } /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups @@ -42157,37 +42771,35 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - // use typesRoot and fallback to directory that contains tsconfig or current directory if typesRoot is not set - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); + var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; // Check primary library paths - if (rootDir !== undefined) { - var effectivePrimarySearchPaths = options.typesSearchPaths || defaultLibrarySearchPaths; - for (var _i = 0, effectivePrimarySearchPaths_1 = effectivePrimarySearchPaths; _i < effectivePrimarySearchPaths_1.length; _i++) { - var searchPath = effectivePrimarySearchPaths_1[_i]; - var primaryPath = ts.combinePaths(rootDir, searchPath); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, primaryPath); - } - var candidate = ts.combinePaths(primaryPath, typeReferenceDirectiveName); + if (typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { @@ -42211,9 +42823,6 @@ var ts; if (containingFile) { initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); } - else { - initialLocationForSecondaryLookup = rootDir; - } if (initialLocationForSecondaryLookup !== undefined) { // check secondary locations if (traceEnabled) { @@ -42808,25 +43417,12 @@ var ts; } } } - function getDefaultTypeDirectiveNames(rootPath) { - var localTypes = ts.combinePaths(rootPath, "types"); - var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); - var result = []; - if (ts.sys.directoryExists(localTypes)) { - result = result.concat(ts.sys.getDirectories(localTypes)); - } - if (ts.sys.directoryExists(npmTypes)) { - result = result.concat(ts.sys.getDirectories(npmTypes)); - } - return result; - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { - getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -42839,6 +43435,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; } @@ -42894,21 +43491,36 @@ var ts; } return resolutions; } - function getDefaultTypeDirectiveNames(options, rootFiles, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + /** + * Given a set of options and a set of root files, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { // Use explicit type list from tsconfig.json if (options.types) { return options.types; } - // or load all types from the automatic type import fields - if (host && host.getDefaultTypeDirectiveNames) { - var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - if (commonRoot) { - return host.getDefaultTypeDirectiveNames(commonRoot); + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + result = result.concat(host.getDirectories(root)); + } } } - return undefined; + return result; } - ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -42948,10 +43560,12 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); - // load type declarations specified via 'types' argument - var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, /*containingFile*/ undefined); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); } @@ -43026,8 +43640,8 @@ var ts; // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = {}; - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var sourceFile = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -43048,10 +43662,9 @@ var ts; (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs) || (oldOptions.rootDir !== options.rootDir) || - (oldOptions.typesSearchPaths !== options.typesSearchPaths) || (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.typesRoot !== options.typesRoot) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; @@ -43383,8 +43996,20 @@ var ts; } break; case 145 /* PropertyDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; + var propertyDeclaration = node; + if (propertyDeclaration.modifiers) { + for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 113 /* StaticKeyword */) { + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + } + } + } + if (checkTypeAnnotation(node.type)) { + return true; + } + break; case 224 /* EnumDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; @@ -43530,10 +44155,13 @@ var ts; // This type of declaration is permitted only in the global module. // The StringLiteral must specify a top - level external module name. // Relative external module names are not permitted - // NOTE: body of ambient module is always a module block - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, /*inAmbientModule*/ true); + // NOTE: body of ambient module is always a module block, if it exists + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } } } } @@ -43696,7 +44324,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_name_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); } if (saveResolution) { resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective; @@ -43868,10 +44496,6 @@ var ts; var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - // Cannot specify module gen target of es6 when below es6 - if (options.module === ts.ModuleKind.ES6 && languageVersion < 2 /* ES6 */) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); - } // Cannot specify module gen that isn't amd or system with --out if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { @@ -44278,8 +44902,13 @@ var ts; } }, { - name: "typesRoot", - type: "string" + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + } }, { name: "types", @@ -44348,6 +44977,10 @@ var ts; }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, + { + name: "disableProjectSizeLimit", + type: "boolean" + }, { name: "strictNullChecks", type: "boolean", @@ -44418,7 +45051,15 @@ var ts; ts.parseCustomTypeOption = parseCustomTypeOption; /* @internal */ function parseListTypeOption(opt, value, errors) { - var values = trimString((value || "")).split(","); + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); switch (opt.element.type) { case "number": return ts.map(values, parseInt); @@ -44478,8 +45119,11 @@ var ts; i++; break; case "list": - options[opt.name] = parseListTypeOption(opt, args[i], errors); - i++; + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } break; // If not a primitive, the possible types are specified in what is effectively a map of options. default: @@ -44590,7 +45234,7 @@ var ts; } // Skip over any minified JavaScript files (ending in ".min.js") // Skip over dotted files and folders as well - var IgnoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -44605,72 +45249,59 @@ var ts; var options = ts.extend(existingOptions, compilerOptions); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; - var fileNames = getFileNames(errors); + var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, - errors: errors + errors: errors, + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { - var fileNames = []; + var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { - fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = json["files"]; } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); } } - else { - var filesSeen = {}; - var exclude = []; - if (ts.isArray(json["exclude"])) { - exclude = json["exclude"]; + var includeSpecs; + if (ts.hasProperty(json, "include")) { + if (ts.isArray(json["include"])) { + includeSpecs = json["include"]; } else { - // by default exclude node_modules, and any specificied output directory - exclude = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - exclude.push(outDir); - } - exclude = ts.map(exclude, function (e) { return ts.getNormalizedAbsolutePath(e, basePath); }); - var supportedExtensions = ts.getSupportedExtensions(options); - ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); - // Get files of supported extensions in their order of resolution - for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; - var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); - for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { - var fileName = filesInDirWithExtension_1[_a]; - // .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension, - // lets pick them when its turn comes up - if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { - continue; - } - if (IgnoreFileNamePattern.test(fileName)) { - continue; - } - // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files) - // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation - if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { - var baseName = fileName.substr(0, fileName.length - extension.length); - if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { - continue; - } - } - filesSeen[fileName] = true; - fileNames.push(fileName); - } + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); } } - if (ts.hasProperty(json, "excludes") && !ts.hasProperty(json, "exclude")) { + var excludeSpecs; + if (ts.hasProperty(json, "exclude")) { + if (ts.isArray(json["exclude"])) { + excludeSpecs = json["exclude"]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + } + } + else if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - return fileNames; + else { + // By default, exclude common package folders + excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + } + // Always exclude the output directory unless explicitly included + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } + if (fileNames === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; @@ -44752,6 +45383,273 @@ var ts; function trimString(s) { return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path with multiple recursive directory wildcards. + * Matches **\** and **\a\**, but not **\a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \*\* # matches a recursive directory wildcard "**" + * ($|\/) # matches either the end of the string or a directory separator. + */ + var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + /** + * Expands an array of file specifications. + * + * @param fileNames The literal file names to include. + * @param include The wildcard file specifications to include. + * @param exclude The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + basePath = ts.normalizePath(basePath); + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. + var literalFileMap = {}; + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. + var wildcardFileMap = {}; + if (include) { + include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false); + } + if (exclude) { + exclude = validateSpecs(exclude, errors, /*allowTrailingRecursion*/ true); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. + var supportedExtensions = ts.getSupportedExtensions(options); + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (fileNames) { + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var file = ts.combinePaths(basePath, fileName); + literalFileMap[keyMapper(file)] = file; + } + } + if (include && include.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + var file = _b[_a]; + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + if (ignoreFileNamePattern.test(file)) { + continue; + } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + wildcardFileMap[key] = file; + } + } + } + var literalFiles = ts.reduceProperties(literalFileMap, addFileToOutput, []); + var wildcardFiles = ts.reduceProperties(wildcardFileMap, addFileToOutput, []); + wildcardFiles.sort(host.useCaseSensitiveFileNames ? ts.compareStrings : ts.compareStringsCaseInsensitive); + return { + fileNames: literalFiles.concat(wildcardFiles), + wildcardDirectories: wildcardDirectories + }; + } + function validateSpecs(specs, errors, allowTrailingRecursion) { + var validSpecs = []; + for (var _i = 0, specs_2 = specs; _i < specs_2.length; _i++) { + var spec = specs_2[_i]; + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + } + else { + validSpecs.push(spec); + } + } + return validSpecs; + } + /** + * Gets directories in a set of include patterns that should be watched for changes. + */ + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var name_35 = ts.combinePaths(path, file); + if (excludeRegex && excludeRegex.test(name_35)) { + continue; + } + var match = wildcardDirectoryPattern.exec(name_35); + if (match) { + var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); + var flags = watchRecursivePattern.test(name_35) ? 1 /* Recursive */ : 0 /* None */; + var existingFlags = ts.getProperty(wildcardDirectories, key); + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + // Remove any subpaths under an existing recursively watched directory. + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + return true; + } + } + return false; + } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + delete wildcardFiles[lowerPriorityPath]; + } + } + /** + * Adds a file to an array of files. + * + * @param output The output array. + * @param file The file path. + */ + function addFileToOutput(output, file) { + output.push(file); + return output; + } + /** + * Gets a case sensitive key. + * + * @param key The original key. + */ + function caseSensitiveKeyMapper(key) { + return key; + } + /** + * Gets a case insensitive key. + * + * @param key The original key. + */ + function caseInsensitiveKeyMapper(key) { + return key.toLowerCase(); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -44929,12 +45827,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_35 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_35); + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_35); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -44947,14 +45845,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_35); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_35, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -45100,689 +45998,586 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile, compilerOptions) { - // TODO: Handle JS files differently in 'navbar' calls for now, but ideally we should unify - // the 'navbar' and 'navto' logic for TypeScript and JavaScript. - if (ts.isSourceFileJavaScript(sourceFile)) { - return getJsNavigationBarItems(sourceFile, compilerOptions); + function getNavigationBarItems(sourceFile) { + curSourceFile = sourceFile; + var result = ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. + var curSourceFile; + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); } - return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); - function getIndent(node) { - var indent = 1; // Global node is the only one with indent 0. - var current = node.parent; - while (current) { - switch (current.kind) { - case 225 /* ModuleDeclaration */: - // If we have a module declared as A.B.C, it is more "intuitive" - // to say it only has a single layer of depth - do { - current = current.parent; - } while (current.kind === 225 /* ModuleDeclaration */); - // fall through - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: - indent++; + else { + parent.children = [child]; + } + } + /* + For performance, we keep navigation bar parents on a stack rather than passing them through each recursion. + `parent` is the current parent and is *not* stored in parentsStack. + `startNode` sets a new parent and `endNode` returns to the previous parent. + */ + var parentsStack = []; + var parent; + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + /** + * Add a new level of NavigationBarNodes. + * This pushes to the stack, so you must call `endNode` when you are done adding to this node. + */ + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + // Save the old parent + parentsStack.push(parent); + parent = navNode; + } + /** Call after calling `startNode` and adding children to it. */ + function endNode() { + if (parent.children) { + mergeChildren(parent.children); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ + function addChildrenRecursively(node) { + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 148 /* Constructor */: + // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + // Parameter properties are children of the class, not the constructor. + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } } - current = current.parent; - } - return indent; - } - function getChildNodes(nodes) { - var childNodes = []; - function visit(node) { - switch (node.kind) { - case 200 /* VariableStatement */: - ts.forEach(node.declarationList.declarations, visit); - break; - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: - ts.forEach(node.elements, visit); - break; - case 236 /* ExportDeclaration */: - // Handle named exports case e.g.: - // export {a, b as B} from "mod"; - if (node.exportClause) { - ts.forEach(node.exportClause.elements, visit); + break; + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 146 /* MethodSignature */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 231 /* ImportClause */: + var importClause = node; + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addLeafNode(importClause); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 232 /* NamespaceImport */) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); } - break; - case 230 /* ImportDeclaration */: - var importClause = node.importClause; - if (importClause) { - // Handle default import case e.g.: - // import d from "mod"; - if (importClause.name) { - childNodes.push(importClause); - } - // Handle named bindings in imports e.g.: - // import * as NS from "mod"; - // import {a, b as B} from "mod"; - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232 /* NamespaceImport */) { - childNodes.push(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, visit); - } - } - } - break; - case 169 /* BindingElement */: - case 218 /* VariableDeclaration */: - if (ts.isBindingPattern(node.name)) { - visit(node.name); - break; - } - // Fall through - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 225 /* ModuleDeclaration */: - case 220 /* FunctionDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: - case 223 /* TypeAliasDeclaration */: - childNodes.push(node); - break; + } } - } - // for (let i = 0, n = nodes.length; i < n; i++) { - // let node = nodes[i]; - // if (node.kind === SyntaxKind.ClassDeclaration || - // node.kind === SyntaxKind.EnumDeclaration || - // node.kind === SyntaxKind.InterfaceDeclaration || - // node.kind === SyntaxKind.ModuleDeclaration || - // node.kind === SyntaxKind.FunctionDeclaration) { - // childNodes.push(node); - // } - // else if (node.kind === SyntaxKind.VariableStatement) { - // childNodes.push.apply(childNodes, (node).declarations); - // } - // } - ts.forEach(nodes, visit); - return sortNodes(childNodes); - } - function getTopLevelNodes(node) { - var topLevelNodes = []; - topLevelNodes.push(node); - addTopLevelNodes(node.statements, topLevelNodes); - return topLevelNodes; - } - function sortNodes(nodes) { - return nodes.slice(0).sort(function (n1, n2) { - if (n1.name && n2.name) { - return localeCompareFix(ts.getPropertyNameForPropertyNameNode(n1.name), ts.getPropertyNameForPropertyNameNode(n2.name)); + break; + case 169 /* BindingElement */: + case 218 /* VariableDeclaration */: + var decl = node; + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } - else if (n1.name) { - return 1; - } - else if (n2.name) { - return -1; + else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { + // For `const x = function() {}`, just use the function node, not the const. + addChildrenRecursively(decl.initializer); } else { - return n1.kind - n2.kind; + addNodeWithRecursiveChild(decl, decl.initializer); } - }); - // node 0.10 treats "a" as greater than "B". - // For consistency, sort alphabetically, falling back to which is lower-case. - function localeCompareFix(a, b) { - var cmp = a.toLowerCase().localeCompare(b.toLowerCase()); - if (cmp !== 0) - return cmp; - // Return the *opposite* of the `<` operator, which works the same in node 0.10 and 6.0. - return a < b ? 1 : a > b ? -1 : 0; - } - } - function addTopLevelNodes(nodes, topLevelNodes) { - nodes = sortNodes(nodes); - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; - switch (node.kind) { - case 221 /* ClassDeclaration */: - topLevelNodes.push(node); - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 147 /* MethodDeclaration */ || member.kind === 148 /* Constructor */) { - if (member.body) { - // We do not include methods that does not have child functions in it, because of duplications. - if (hasNamedFunctionDeclarations(member.body.statements)) { - topLevelNodes.push(member); - } - addTopLevelNodes(member.body.statements, topLevelNodes); - } + break; + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + addNodeWithRecursiveChild(node, node.body); + break; + case 224 /* EnumDeclaration */: + startNode(node); + for (var _d = 0, _e = node.members; _d < _e.length; _d++) { + var member = _e[_d]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 222 /* InterfaceDeclaration */: + startNode(node); + for (var _f = 0, _g = node.members; _f < _g.length; _f++) { + var member = _g[_f]; + addChildrenRecursively(member); + } + endNode(); + break; + case 225 /* ModuleDeclaration */: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 238 /* ExportSpecifier */: + case 229 /* ImportEqualsDeclaration */: + case 153 /* IndexSignature */: + case 151 /* CallSignature */: + case 152 /* ConstructSignature */: + case 223 /* TypeAliasDeclaration */: + addLeafNode(node); + break; + default: + if (node.jsDocComments) { + for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { + var jsDocComment = _j[_h]; + for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { + var tag = _l[_k]; + if (tag.kind === 279 /* JSDocTypedefTag */) { + addLeafNode(tag); } } - break; - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - topLevelNodes.push(node); - break; - case 225 /* ModuleDeclaration */: - var moduleDeclaration = node; - topLevelNodes.push(node); - addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); - break; - case 220 /* FunctionDeclaration */: - var functionDeclaration = node; - if (isTopLevelFunctionDeclaration(functionDeclaration)) { - topLevelNodes.push(node); - addTopLevelNodes(functionDeclaration.body.statements, topLevelNodes); - } - break; + } } - } + ts.forEachChild(node, addChildrenRecursively); } - function hasNamedFunctionDeclarations(nodes) { - for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { - var s = nodes_5[_i]; - if (s.kind === 220 /* FunctionDeclaration */ && !isEmpty(s.name.text)) { + } + /** Merge declarations of the same kind. */ + function mergeChildren(children) { + var nameToItems = {}; + ts.filterMutate(children, function (child) { + var decl = child.node; + var name = decl.name && nodeText(decl.name); + if (!name) { + // Anonymous items are never merged. + return true; + } + var itemsWithSameName = ts.getProperty(nameToItems, name); + if (!itemsWithSameName) { + nameToItems[name] = child; + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child)) { + return false; + } + nameToItems[name] = [itemWithSameName, child]; + return true; + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); return true; } + return false; } - return false; - } - function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 220 /* FunctionDeclaration */) { - // A function declaration is 'top level' if it contains any function declarations - // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === 199 /* Block */) { - // Proper function declarations can only have identifier names - if (hasNamedFunctionDeclarations(functionDeclaration.body.statements)) { - return true; - } - // Or if it is not parented by another function. I.e all functions at module scope are 'top level'. - if (!ts.isFunctionBlock(functionDeclaration.parent)) { - return true; - } - else { - // We have made sure that a grand parent node exists with 'isFunctionBlock()' above. - var grandParentKind = functionDeclaration.parent.parent.kind; - if (grandParentKind === 147 /* MethodDeclaration */ || - grandParentKind === 148 /* Constructor */) { - return true; - } - } + }); + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a, b) { + return a.kind === b.kind && (a.kind !== 225 /* ModuleDeclaration */ || areSameModule(a, b)); + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a, b) { + if (a.body.kind !== b.body.kind) { + return false; } - } - return false; - } - function getItemsWorker(nodes, createItem) { - var items = []; - var keyToItem = {}; - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var child = nodes_6[_i]; - var item = createItem(child); - if (item !== undefined) { - if (item.text.length > 0) { - var key = item.text + "-" + item.kind + "-" + item.indent; - var itemWithSameName = keyToItem[key]; - if (itemWithSameName) { - // We had an item with the same name. Merge these items together. - merge(itemWithSameName, item); - } - else { - keyToItem[key] = item; - items.push(item); - } - } + if (a.body.kind !== 225 /* ModuleDeclaration */) { + return true; } + return areSameModule(a.body, b.body); } - return items; } + /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { - // First, add any spans in the source to the target. - ts.addRange(target.spans, source.spans); - if (source.childItems) { - if (!target.childItems) { - target.childItems = []; - } - // Next, recursively merge or add any children in the source as appropriate. - outer: for (var _i = 0, _a = source.childItems; _i < _a.length; _i++) { - var sourceChild = _a[_i]; - for (var _b = 0, _c = target.childItems; _b < _c.length; _b++) { - var targetChild = _c[_b]; - if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) { - // Found a match. merge them. - merge(targetChild, sourceChild); - continue outer; - } - } - // Didn't find a match, just add this child to the list. - target.childItems.push(sourceChild); - } + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); + } + var _a; + } + } + /** Recursively ensure that each NavNode's children are in sorted order. */ + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); + if (name1 && name2) { + var cmp = localeCompareFix(name1, name2); + return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + else { + return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + } + // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. + var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". + var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + // This isn't perfect, but it passes all of our tests. + for (var i = 0; i < Math.min(a.length, b.length); i++) { + var chA = a.charAt(i), chB = b.charAt(i); + if (chA === "\"" && chB === "'") { + return 1; + } + if (chA === "'" && chB === "\"") { + return -1; + } + var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + if (cmp !== 0) { + return cmp; } } - function createChildItem(node) { - switch (node.kind) { - case 142 /* Parameter */: - if (ts.isBindingPattern(node.name)) { - break; - } - if ((node.flags & 1023 /* Modifier */) === 0) { - return undefined; - } - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 149 /* GetAccessor */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 150 /* SetAccessor */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 153 /* IndexSignature */: - return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 224 /* EnumDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); - case 255 /* EnumMember */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 225 /* ModuleDeclaration */: - return createItem(node, getModuleName(node), ts.ScriptElementKind.moduleElement); - case 222 /* InterfaceDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); - case 223 /* TypeAliasDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.typeElement); - case 151 /* CallSignature */: - return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 152 /* ConstructSignature */: - return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 221 /* ClassDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.classElement); - case 220 /* FunctionDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - var variableDeclarationNode = void 0; - var name_36; - if (node.kind === 169 /* BindingElement */) { - name_36 = node.name; - variableDeclarationNode = node; - // binding elements are added only for variable declarations - // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(variableDeclarationNode !== undefined); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_36 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.constElement); - } - else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.letElement); - } - else { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.variableElement); - } - case 148 /* Constructor */: - return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 238 /* ExportSpecifier */: - case 234 /* ImportSpecifier */: - case 229 /* ImportEqualsDeclaration */: - case 231 /* ImportClause */: - case 232 /* NamespaceImport */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); - } - return undefined; - function createItem(node, name, scriptElementKind) { - return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]); - } + return a.length - b.length; + }; + /** + * This differs from getItemName because this is just used for sorting. + * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like. + * So `new()` can still come before an `aardvark` method. + */ + function tryGetName(node) { + if (node.kind === 225 /* ModuleDeclaration */) { + return getModuleName(node); } - function isEmpty(text) { - return !text || text.trim() === ""; + var decl = node; + if (decl.name) { + return ts.getPropertyNameForPropertyNameNode(decl.name); } - function getNavigationBarItem(text, kind, kindModifiers, spans, childItems, indent) { - if (childItems === void 0) { childItems = []; } - if (indent === void 0) { indent = 0; } - if (isEmpty(text)) { + switch (node.kind) { + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 192 /* ClassExpression */: + return getFunctionOrClassName(node); + case 279 /* JSDocTypedefTag */: + return getJSDocTypedefTagName(node); + default: return undefined; + } + } + function getItemName(node) { + if (node.kind === 225 /* ModuleDeclaration */) { + return getModuleName(node); + } + var name = node.name; + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; } + } + switch (node.kind) { + case 256 /* SourceFile */: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + if (node.flags & 512 /* Default */) { + return "default"; + } + return getFunctionOrClassName(node); + case 148 /* Constructor */: + return "constructor"; + case 152 /* ConstructSignature */: + return "new()"; + case 151 /* CallSignature */: + return "()"; + case 153 /* IndexSignature */: + return "[]"; + case 279 /* JSDocTypedefTag */: + return getJSDocTypedefTagName(node); + default: + ts.Debug.fail(); + return ""; + } + } + function getJSDocTypedefTagName(node) { + if (node.name) { + return node.name.text; + } + else { + var parentNode = node.parent && node.parent.parent; + if (parentNode && parentNode.kind === 200 /* VariableStatement */) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (nameIdentifier.kind === 69 /* Identifier */) { + return nameIdentifier.text; + } + } + } + return ""; + } + } + /** Flattens the NavNode tree to a list, keeping only the top-level items. */ + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 224 /* EnumDeclaration */: + case 222 /* InterfaceDeclaration */: + case 225 /* ModuleDeclaration */: + case 256 /* SourceFile */: + case 223 /* TypeAliasDeclaration */: + case 279 /* JSDocTypedefTag */: + return true; + case 148 /* Constructor */: + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return hasSomeImportantChild(item); + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 226 /* ModuleBlock */: + case 256 /* SourceFile */: + case 147 /* MethodDeclaration */: + case 148 /* Constructor */: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.forEach(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 218 /* VariableDeclaration */ && childKind !== 169 /* BindingElement */; + }); + } + } + } + // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. + var emptyChildItemArray = []; + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { return { - text: text, - kind: kind, - kindModifiers: kindModifiers, - spans: spans, - childItems: childItems, - indent: indent, + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, bolded: false, grayed: false }; } - function createTopLevelItem(node) { - switch (node.kind) { - case 256 /* SourceFile */: - return createSourceFileItem(node); - case 221 /* ClassDeclaration */: - return createClassItem(node); - case 147 /* MethodDeclaration */: - case 148 /* Constructor */: - return createMemberFunctionLikeItem(node); - case 224 /* EnumDeclaration */: - return createEnumItem(node); - case 222 /* InterfaceDeclaration */: - return createInterfaceItem(node); - case 225 /* ModuleDeclaration */: - return createModuleItem(node); - case 220 /* FunctionDeclaration */: - return createFunctionItem(node); - case 223 /* TypeAliasDeclaration */: - return createTypeAliasItem(node); - } - return undefined; - function createModuleItem(node) { - var moduleName = getModuleName(node); - var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem); - return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createFunctionItem(node) { - if (node.body && node.body.kind === 199 /* Block */) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return undefined; } - function createTypeAliasItem(node) { - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.typeElement, ts.getNodeModifiers(node), [getNodeSpan(node)], [], getIndent(node)); - } - function createMemberFunctionLikeItem(node) { - if (node.body && node.body.kind === 199 /* Block */) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - var scriptElementKind = void 0; - var memberFunctionName = void 0; - if (node.kind === 147 /* MethodDeclaration */) { - memberFunctionName = ts.getPropertyNameForPropertyNameNode(node.name); - scriptElementKind = ts.ScriptElementKind.memberFunctionElement; - } - else { - memberFunctionName = "constructor"; - scriptElementKind = ts.ScriptElementKind.constructorImplementationElement; - } - return getNavigationBarItem(memberFunctionName, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - return undefined; - } - function createSourceFileItem(node) { - var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); - var rootName = ts.isExternalModule(node) - ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\"" - : ""; - return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems); - } - function createClassItem(node) { - var childItems; - if (node.members) { - var constructor = ts.forEach(node.members, function (member) { - return member.kind === 148 /* Constructor */ && member; - }); - // Add the constructor parameters in as children of the class (for property parameters). - // Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that - // are not properties will be filtered out later by createChildItem. - var nodes = removeDynamicallyNamedProperties(node); - if (constructor) { - ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); })); - } - childItems = getItemsWorker(sortNodes(nodes), createChildItem); - } - var nodeName = !node.name ? "default" : node.name.text; - return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createEnumItem(node) { - var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createInterfaceItem(node) { - var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - } - function getModuleName(moduleDeclaration) { - // We want to maintain quotation marks. - if (ts.isAmbientModule(moduleDeclaration)) { - return getTextOfNode(moduleDeclaration.name); - } - // Otherwise, we need to aggregate each identifier to build up the qualified name. - var result = []; - result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { - moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); - } - return result.join("."); - } - function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 140 /* ComputedPropertyName */; }); - } - /** - * Like removeComputedProperties, but retains the properties with well known symbol names - */ - function removeDynamicallyNamedProperties(node) { - return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); - } - function getInnermostModule(node) { - while (node.body.kind === 225 /* ModuleDeclaration */) { - node = node.body; - } - return node; - } - function getNodeSpan(node) { - return node.kind === 256 /* SourceFile */ - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getTextOfNode(node) { - return ts.getTextOfNodeFromSourceText(sourceFile.text, node); + return spans; } } - NavigationBar.getNavigationBarItems = getNavigationBarItems; - function getJsNavigationBarItems(sourceFile, compilerOptions) { - var anonFnText = ""; - var anonClassText = ""; - var indent = 0; - var rootName = ts.isExternalModule(sourceFile) ? - "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" - : ""; - var sourceFileItem = getNavBarItem(rootName, ts.ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]); - var topItem = sourceFileItem; - // Walk the whole file, because we want to also find function expressions - which may be in variable initializer, - // call arguments, expressions, etc... - ts.forEachChild(sourceFile, visitNode); - function visitNode(node) { - var newItem = createNavBarItem(node); - if (newItem) { - topItem.childItems.push(newItem); - } - if (node.jsDocComments && node.jsDocComments.length > 0) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - visitNode(jsDocComment); - } - } - // Add a level if traversing into a container - if (newItem && (ts.isFunctionLike(node) || ts.isClassLike(node))) { - var lastTop = topItem; - indent++; - topItem = newItem; - ts.forEachChild(node, visitNode); - topItem = lastTop; - indent--; - // If the last item added was an anonymous function expression, and it had no children, discard it. - if (newItem && newItem.text === anonFnText && newItem.childItems.length === 0) { - topItem.childItems.pop(); - } - } - else { - ts.forEachChild(node, visitNode); - } - } - function createNavBarItem(node) { - switch (node.kind) { - case 218 /* VariableDeclaration */: - // Only add to the navbar if at the top-level of the file - // Note: "const" and "let" are also SyntaxKind.VariableDeclarations - if (node.parent /*VariableDeclarationList*/.parent /*VariableStatement*/ - .parent /*SourceFile*/.kind !== 256 /* SourceFile */) { - return undefined; + // TODO: GH#9145: We should just use getNodeKind. No reason why navigationBar and navigateTo should have different behaviors. + function nodeKind(node) { + switch (node.kind) { + case 256 /* SourceFile */: + return ts.ScriptElementKind.moduleElement; + case 255 /* EnumMember */: + return ts.ScriptElementKind.memberVariableElement; + case 218 /* VariableDeclaration */: + case 169 /* BindingElement */: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169 /* BindingElement */) { + name_38 = node.name; + variableDeclarationNode = node; + // binding elements are added only for variable declarations + // bubble up to the containing variable declaration + while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { + variableDeclarationNode = variableDeclarationNode.parent; } - // If it is initialized with a function expression, handle it when we reach the function expression node - var varDecl = node; - if (varDecl.initializer && (varDecl.initializer.kind === 179 /* FunctionExpression */ || - varDecl.initializer.kind === 180 /* ArrowFunction */ || - varDecl.initializer.kind === 192 /* ClassExpression */)) { - return undefined; - } - // Fall through - case 220 /* FunctionDeclaration */: - case 221 /* ClassDeclaration */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - // "export default function().." looks just like a regular function/class declaration, except with the 'default' flag - var name_37 = node.flags && (node.flags & 512 /* Default */) && !node.name ? "default" : - node.kind === 148 /* Constructor */ ? "constructor" : - ts.declarationNameToString(node.name); - return getNavBarItem(name_37, getScriptKindForElementKind(node.kind), [getNodeSpan(node)]); - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 192 /* ClassExpression */: - return getDefineModuleItem(node) || getFunctionOrClassExpressionItem(node); - case 147 /* MethodDeclaration */: - var methodDecl = node; - return getNavBarItem(ts.declarationNameToString(methodDecl.name), ts.ScriptElementKind.memberFunctionElement, [getNodeSpan(node)]); - case 235 /* ExportAssignment */: - // e.g. "export default " - return getNavBarItem("default", ts.ScriptElementKind.variableElement, [getNodeSpan(node)]); - case 231 /* ImportClause */: - if (!node.name) { - // No default import (this node is still a parent of named & namespace imports, which are handled below) - return undefined; - } - // fall through - case 234 /* ImportSpecifier */: // e.g. 'id' in: import {id} from 'mod' (in NamedImports, in ImportClause) - case 232 /* NamespaceImport */: // e.g. '* as ns' in: import * as ns from 'mod' (in ImportClause) - case 238 /* ExportSpecifier */: - // Export specifiers are only interesting if they are reexports from another module, or renamed, else they are already globals - if (node.kind === 238 /* ExportSpecifier */) { - if (!node.parent.parent.moduleSpecifier && !node.propertyName) { - return undefined; - } - } - var decl = node; - if (!decl.name) { - return undefined; - } - var declName = ts.declarationNameToString(decl.name); - return getNavBarItem(declName, ts.ScriptElementKind.constElement, [getNodeSpan(node)]); - case 279 /* JSDocTypedefTag */: - if (node.name) { - return getNavBarItem(node.name.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69 /* Identifier */) { - return getNavBarItem(nameIdentifier.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - } - } - } - default: - return undefined; - } - } - function getNavBarItem(text, kind, spans, kindModifiers) { - if (kindModifiers === void 0) { kindModifiers = ts.ScriptElementKindModifier.none; } - return { - text: text, kind: kind, kindModifiers: kindModifiers, spans: spans, childItems: [], indent: indent, bolded: false, grayed: false - }; - } - function getDefineModuleItem(node) { - if (node.kind !== 179 /* FunctionExpression */ && node.kind !== 180 /* ArrowFunction */) { - return undefined; - } - // No match if this is not a call expression to an identifier named 'define' - if (node.parent.kind !== 174 /* CallExpression */) { - return undefined; - } - var callExpr = node.parent; - if (callExpr.expression.kind !== 69 /* Identifier */ || callExpr.expression.getText() !== "define") { - return undefined; - } - // Return a module of either the given text in the first argument, or of the source file path - var defaultName = node.getSourceFile().fileName; - if (callExpr.arguments[0].kind === 9 /* StringLiteral */) { - defaultName = (callExpr.arguments[0]).text; - } - return getNavBarItem(defaultName, ts.ScriptElementKind.moduleElement, [getNodeSpan(node.parent)]); - } - function getFunctionOrClassExpressionItem(node) { - if (node.kind !== 179 /* FunctionExpression */ && - node.kind !== 180 /* ArrowFunction */ && - node.kind !== 192 /* ClassExpression */) { - return undefined; - } - var fnExpr = node; - var fnName; - if (fnExpr.name && ts.getFullWidth(fnExpr.name) > 0) { - // The expression has an identifier, so use that as the name - fnName = ts.declarationNameToString(fnExpr.name); - } - else { - // See if it is a var initializer. If so, use the var name. - if (fnExpr.parent.kind === 218 /* VariableDeclaration */) { - fnName = ts.declarationNameToString(fnExpr.parent.name); - } - else if (fnExpr.parent.kind === 187 /* BinaryExpression */ && - fnExpr.parent.operatorToken.kind === 56 /* EqualsToken */) { - fnName = fnExpr.parent.left.getText(); - } - else if (fnExpr.parent.kind === 253 /* PropertyAssignment */ && - fnExpr.parent.name) { - fnName = fnExpr.parent.name.getText(); + ts.Debug.assert(!!variableDeclarationNode); } else { - fnName = node.kind === 192 /* ClassExpression */ ? anonClassText : anonFnText; + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; } - } - var scriptKind = node.kind === 192 /* ClassExpression */ ? ts.ScriptElementKind.classElement : ts.ScriptElementKind.functionElement; - return getNavBarItem(fnName, scriptKind, [getNodeSpan(node)]); - } - function getNodeSpan(node) { - return node.kind === 256 /* SourceFile */ - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getScriptKindForElementKind(kind) { - switch (kind) { - case 218 /* VariableDeclaration */: + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { return ts.ScriptElementKind.variableElement; - case 220 /* FunctionDeclaration */: - return ts.ScriptElementKind.functionElement; - case 221 /* ClassDeclaration */: - return ts.ScriptElementKind.classElement; - case 148 /* Constructor */: - return ts.ScriptElementKind.constructorImplementationElement; - case 149 /* GetAccessor */: - return ts.ScriptElementKind.memberGetAccessorElement; - case 150 /* SetAccessor */: - return ts.ScriptElementKind.memberSetAccessorElement; - default: - return "unknown"; - } + } + case 180 /* ArrowFunction */: + return ts.ScriptElementKind.functionElement; + case 279 /* JSDocTypedefTag */: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); } - return sourceFileItem.childItems; } - NavigationBar.getJsNavigationBarItems = getJsNavigationBarItems; + function getModuleName(moduleDeclaration) { + // We want to maintain quotation marks. + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + // Otherwise, we need to aggregate each identifier to build up the qualified name. + var result = []; + result.push(moduleDeclaration.name.text); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + moduleDeclaration = moduleDeclaration.body; + result.push(moduleDeclaration.name.text); + } + return result.join("."); + } + /** + * For 'module A.B.C', we want to get the node for 'C'. + * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. + */ + function getInteriorModule(decl) { + return decl.body.kind === 225 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 140 /* ComputedPropertyName */; + } + function getNodeSpan(node) { + return node.kind === 256 /* SourceFile */ + ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) + : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); + } + function getFunctionOrClassName(node) { + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + else if (node.parent.kind === 218 /* VariableDeclaration */) { + return ts.declarationNameToString(node.parent.name); + } + else if (node.parent.kind === 187 /* BinaryExpression */ && + node.parent.operatorToken.kind === 56 /* EqualsToken */) { + return nodeText(node.parent.left); + } + else if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.name) { + return nodeText(node.parent.name); + } + else if (node.flags & 512 /* Default */) { + return "default"; + } + else { + return ts.isClassLike(node) ? "" : ""; + } + } + function isFunctionOrClassExpression(node) { + return node.kind === 179 /* FunctionExpression */ || node.kind === 180 /* ArrowFunction */ || node.kind === 192 /* ClassExpression */; + } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); /* @internal */ @@ -47848,9 +48643,9 @@ var ts; } getTypingNamesFromSourceFileNames(fileNames); // Add the cached typing locations for inferred typings that are already installed - for (var name_38 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_38) && !inferredTypings[name_38]) { - inferredTypings[name_38] = packageNameToTypingLocation[name_38]; + for (var name_39 in packageNameToTypingLocation) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } // Remove typings that the user has added to the exclude list @@ -47936,9 +48731,9 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, "*.json", /*exclude*/ undefined, /*depth*/ 2); - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); if (ts.getBaseFileName(normalizedFileName) !== "package.json") { continue; @@ -48679,9 +49474,9 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_39 in o) { - if (o[name_39] === rule) { - return name_39; + for (var name_40 in o) { + if (o[name_40] === rule) { + return name_40; } } throw new Error("Unknown rule"); @@ -50686,6 +51481,7 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// +/// /// /// /// @@ -50825,8 +51621,8 @@ var ts; var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -50961,7 +51757,7 @@ var ts; addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); } // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 225 /* ModuleDeclaration */ && declaration.body.kind === 225 /* ModuleDeclaration */) { + if (declaration.kind === 225 /* ModuleDeclaration */ && declaration.body && declaration.body.kind === 225 /* ModuleDeclaration */) { return; } if ((declaration.kind === 179 /* FunctionExpression */ || declaration.kind === 180 /* ArrowFunction */) && @@ -51797,11 +52593,11 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptions_stringToEnum; + var commandLineOptionsStringToEnum; /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ function fixupCompilerOptions(options, diagnostics) { // Lazily create this value to fix module loading errors. - commandLineOptions_stringToEnum = commandLineOptions_stringToEnum || ts.filter(ts.optionDeclarations, function (o) { + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); @@ -51822,8 +52618,8 @@ var ts; } } }; - for (var _i = 0, commandLineOptions_stringToEnum_1 = commandLineOptions_stringToEnum; _i < commandLineOptions_stringToEnum_1.length; _i++) { - var opt = commandLineOptions_stringToEnum_1[_i]; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; _loop_2(opt); } return options; @@ -51848,6 +52644,17 @@ var ts; // We are not returning a sourceFile for lib file when asked by the program, // so pass --noLib to avoid reporting a file not found error. options.noLib = true; + // Clear out other settings that would not be used in transpiling this module + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; // We are not doing a full typecheck, we are not resolving the whole context, // so pass --noResolve to avoid reporting missing file errors. options.noResolve = true; @@ -51882,7 +52689,8 @@ var ts; getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; } + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -51970,7 +52778,7 @@ var ts; var buckets = {}; var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + settings.typesRoot + "|" + settings.typesSearchPaths + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); + return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = ts.lookUp(buckets, key); @@ -52716,7 +53524,8 @@ var ts; oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs); + oldSettings.allowJs !== newSettings.allowJs || + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -52739,8 +53548,10 @@ var ts; return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); }, directoryExists: function (directoryName) { - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; } }; if (host.trace) { @@ -53588,8 +54399,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_40 = element.propertyName || element.name; - existingImportsOrExports[name_40.text] = true; + var name_41 = element.propertyName || element.name; + existingImportsOrExports[name_41.text] = true; } if (ts.isEmpty(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -53709,14 +54520,14 @@ var ts; var entries = []; var target = program.getCompilerOptions().target; var nameTable = getNameTable(sourceFile); - for (var name_41 in nameTable) { + for (var name_42 in nameTable) { // Skip identifiers produced only from the current location - if (nameTable[name_41] === position) { + if (nameTable[name_42] === position) { continue; } - if (!uniqueNames[name_41]) { - uniqueNames[name_41] = name_41; - var displayName = getCompletionEntryDisplayName(name_41, target, /*performCharacterChecks*/ true); + if (!uniqueNames[name_42]) { + uniqueNames[name_42] = name_42; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, /*performCharacterChecks*/ true); if (displayName) { var entry = { name: displayName, @@ -53833,10 +54644,10 @@ var ts; var typeChecker = program.getTypeChecker(); var type = typeChecker.getContextualType(node); if (type) { - var entries_1 = []; - addStringLiteralCompletionsFromType(type, entries_1); - if (entries_1.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_1 }; + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -55136,7 +55947,8 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference + isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isDefinition: false }); } } @@ -55486,7 +56298,8 @@ var ts; references: [{ fileName: sourceFile.fileName, textSpan: ts.createTextSpan(position, searchText.length), - isWriteAccess: false + isWriteAccess: false, + isDefinition: false }] }); } @@ -55964,7 +56777,8 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node) + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) }; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ @@ -56206,7 +57020,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); + return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -56639,7 +57453,8 @@ var ts; return; case 142 /* Parameter */: if (token.parent.name === token) { - return 17 /* parameterName */; + var isThis = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; + return isThis ? 3 /* keyword */ : 17 /* parameterName */; } return; } @@ -58437,6 +59252,7 @@ var ts; function CoreServicesShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } @@ -58444,17 +59260,26 @@ var ts; this.realpath = function (path) { return _this.shimHost.realpath(path); }; } } - CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude, depth) { + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { // Wrap the API changes for 2.0 release. This try/catch // should be removed once TypeScript 2.0 has shipped. - var encoded; try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude), depth); + var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); } catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); + var results = []; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { + var file = _b[_a]; + if (!ts.contains(results, file)) { + results.push(file); + } + } + } + return results; } - return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -58462,6 +59287,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; + CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { + return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -58987,4 +59815,4 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = "1.9"; -/* tslint:enable:no-unused-variable */ +/* tslint:enable:no-unused-variable */ diff --git a/package.json b/package.json index bb476070286..ee6ed62964c 100644 --- a/package.json +++ b/package.json @@ -29,15 +29,48 @@ "node": ">=0.8.0" }, "devDependencies": { - "jake": "latest", - "mocha": "latest", - "chai": "latest", + "@types/browserify": "latest", + "@types/del": "latest", + "@types/glob": "latest", + "@types/gulp": "latest", + "@types/gulp-concat": "latest", + "@types/gulp-help": "latest", + "@types/gulp-newer": "latest", + "@types/gulp-sourcemaps": "latest", + "@types/gulp-typescript": "latest", + "@types/merge2": "latest", + "@types/minimatch": "latest", + "@types/minimist": "latest", + "@types/mkdirp": "latest", + "@types/node": "latest", + "@types/q": "latest", + "@types/run-sequence": "latest", + "@types/through2": "latest", "browserify": "latest", + "chai": "latest", + "del": "latest", + "gulp": "latest", + "gulp-clone": "latest", + "gulp-concat": "latest", + "gulp-help": "latest", + "gulp-insert": "latest", + "gulp-newer": "latest", + "gulp-sourcemaps": "latest", + "gulp-typescript": "latest", + "into-stream": "latest", "istanbul": "latest", + "jake": "latest", + "merge2": "latest", + "minimist": "latest", + "mkdirp": "latest", + "mocha": "latest", "mocha-fivemat-progress-reporter": "latest", + "run-sequence": "latest", + "through2": "latest", + "ts-node": "latest", + "tsd": "latest", "tslint": "next", - "typescript": "next", - "tsd": "latest" + "typescript": "next" }, "scripts": { "pretest": "jake tests", @@ -47,6 +80,7 @@ "build:tests": "jake tests", "start": "node lib/tsc", "clean": "jake clean", + "gulp": "gulp", "jake": "jake", "lint": "jake lint", "setup-hooks": "node scripts/link-hooks.js" diff --git a/scripts/mocha-parallel.js b/scripts/mocha-parallel.js index bf33f68f204..ce40c832b21 100644 --- a/scripts/mocha-parallel.js +++ b/scripts/mocha-parallel.js @@ -245,6 +245,13 @@ function runTests(taskConfigsFolder, run, options, cb) { } } +var nodeModulesPathPrefix = path.resolve("./node_modules/.bin/") + path.delimiter; +if (process.env.path !== undefined) { + process.env.path = nodeModulesPathPrefix + process.env.path; +} else if (process.env.PATH !== undefined) { + process.env.PATH = nodeModulesPathPrefix + process.env.PATH; +} + function spawnProcess(cmd, options) { var shell = process.platform === "win32" ? "cmd" : "/bin/sh"; var prefix = process.platform === "win32" ? "/c" : "-c"; diff --git a/scripts/tslint/objectLiteralSurroundingSpaceRule.ts b/scripts/tslint/objectLiteralSurroundingSpaceRule.ts new file mode 100644 index 00000000000..b527746bf51 --- /dev/null +++ b/scripts/tslint/objectLiteralSurroundingSpaceRule.ts @@ -0,0 +1,42 @@ +import * as Lint from "tslint/lib/lint"; +import * as ts from "typescript"; + + +export class Rule extends Lint.Rules.AbstractRule { + public static LEADING_FAILURE_STRING = "No leading whitespace found on single-line object literal."; + public static TRAILING_FAILURE_STRING = "No trailing whitespace found on single-line object literal."; + public static LEADING_EXCESS_FAILURE_STRING = "Excess leading whitespace found on single-line object literal."; + public static TRAILING_EXCESS_FAILURE_STRING = "Excess trailing whitespace found on single-line object literal."; + + public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { + return this.applyWithWalker(new ObjectLiteralSpaceWalker(sourceFile, this.getOptions())); + } +} + +class ObjectLiteralSpaceWalker extends Lint.RuleWalker { + public visitNode(node: ts.Node) { + if (node.kind === ts.SyntaxKind.ObjectLiteralExpression) { + const literal = node as ts.ObjectLiteralExpression; + const text = literal.getText(); + if (text.match(/^{[^\n]+}$/g)) { + if (text.charAt(1) !== " ") { + const failure = this.createFailure(node.pos, node.getWidth(), Rule.LEADING_FAILURE_STRING); + this.addFailure(failure); + } + if (text.charAt(2) === " ") { + const failure = this.createFailure(node.pos + 2, 1, Rule.LEADING_EXCESS_FAILURE_STRING); + this.addFailure(failure); + } + if (text.charAt(text.length - 2) !== " ") { + const failure = this.createFailure(node.pos, node.getWidth(), Rule.TRAILING_FAILURE_STRING); + this.addFailure(failure); + } + if (text.charAt(text.length - 3) === " ") { + const failure = this.createFailure(node.pos + node.getWidth() - 3, 1, Rule.TRAILING_EXCESS_FAILURE_STRING); + this.addFailure(failure); + } + } + } + super.visitNode(node); + } +} diff --git a/scripts/types/ambient.d.ts b/scripts/types/ambient.d.ts new file mode 100644 index 00000000000..8a86a290bee --- /dev/null +++ b/scripts/types/ambient.d.ts @@ -0,0 +1,22 @@ +declare module "gulp-clone" { + function Clone(): NodeJS.ReadWriteStream; + namespace Clone { + export function sink() : NodeJS.ReadWriteStream & {tap: () => NodeJS.ReadWriteStream}; + } + export = Clone; +} + +declare module "gulp-insert" { + export function append(text: string | Buffer): NodeJS.ReadWriteStream; + export function prepend(text: string | Buffer): NodeJS.ReadWriteStream; + export function wrap(text: string | Buffer, tail: string | Buffer): NodeJS.ReadWriteStream; + export function transform(cb: (contents: string, file: {path: string}) => string): NodeJS.ReadWriteStream; // file is a vinyl file +} + +declare module "into-stream" { + function IntoStream(content: string | Buffer | (string | Buffer)[]): NodeJS.ReadableStream; + namespace IntoStream { + export function obj(content: any): NodeJS.ReadableStream + } + export = IntoStream; +} \ No newline at end of file diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 582fc16981a..d5c4306037d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2473,16 +2473,13 @@ namespace ts { } } - function buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { + function buildDisplayForParametersAndDelimiters(thisParameter: Symbol | undefined, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { writePunctuation(writer, SyntaxKind.OpenParenToken); - if (thisType) { - writeKeyword(writer, SyntaxKind.ThisKeyword); - writePunctuation(writer, SyntaxKind.ColonToken); - writeSpace(writer); - buildTypeDisplay(thisType, writer, enclosingDeclaration, flags, symbolStack); + if (thisParameter) { + buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); } for (let i = 0; i < parameters.length; i++) { - if (i > 0 || thisType) { + if (i > 0 || thisParameter) { writePunctuation(writer, SyntaxKind.CommaToken); writeSpace(writer); } @@ -2538,7 +2535,7 @@ namespace ts { buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); } - buildDisplayForParametersAndDelimiters(signature.thisType, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); } @@ -2981,12 +2978,14 @@ namespace ts { if (func.kind === SyntaxKind.SetAccessor && !hasDynamicName(func)) { const getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); if (getter) { - const signature = getSignatureFromDeclaration(getter); + const getterSignature = getSignatureFromDeclaration(getter); const thisParameter = getAccessorThisParameter(func as AccessorDeclaration); if (thisParameter && declaration === thisParameter) { - return signature.thisType; + // Use the type from the *getter* + Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); } - return getReturnTypeOfSignature(signature); + return getReturnTypeOfSignature(getterSignature); } } // Use contextual parameter type if one is available @@ -3208,14 +3207,13 @@ namespace ts { return undefined; } - function getAnnotatedAccessorThisType(accessor: AccessorDeclaration): Type { - if (accessor) { - const parameter = getAccessorThisParameter(accessor); - if (parameter && parameter.type) { - return getTypeFromTypeNode(accessor.parameters[0].type); - } - } - return undefined; + function getAnnotatedAccessorThisParameter(accessor: AccessorDeclaration): Symbol | undefined { + const parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + + function getThisTypeOfDeclaration(declaration: SignatureDeclaration): Type | undefined { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); } function getTypeOfAccessors(symbol: Symbol): Type { @@ -3898,13 +3896,13 @@ namespace ts { resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], thisType: Type, parameters: Symbol[], + function createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], thisParameter: Symbol | undefined, parameters: Symbol[], resolvedReturnType: Type, typePredicate: TypePredicate, minArgumentCount: number, hasRestParameter: boolean, hasStringLiterals: boolean): Signature { const sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; - sig.thisType = thisType; + sig.thisParameter = thisParameter; sig.resolvedReturnType = resolvedReturnType; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; @@ -3914,7 +3912,7 @@ namespace ts { } function cloneSignature(sig: Signature): Signature { - return createSignature(sig.declaration, sig.typeParameters, sig.thisType, sig.parameters, sig.resolvedReturnType, + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } @@ -4012,8 +4010,9 @@ namespace ts { // Union the result types when more than one signature matches if (unionSignatures.length > 1) { s = cloneSignature(signature); - if (forEach(unionSignatures, sig => sig.thisType)) { - s.thisType = getUnionType(map(unionSignatures, sig => sig.thisType || anyType)); + if (forEach(unionSignatures, sig => sig.thisParameter)) { + const thisType = getUnionType(map(unionSignatures, sig => getTypeOfSymbol(sig.thisParameter) || anyType)); + s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } // Clear resolved return type we possibly got from cloneSignature s.resolvedReturnType = undefined; @@ -4466,7 +4465,7 @@ namespace ts { const parameters: Symbol[] = []; let hasStringLiterals = false; let minArgumentCount = -1; - let thisType: Type = undefined; + let thisParameter: Symbol = undefined; let hasThisParameter: boolean; const isJSConstructSignature = isJSDocConstructSignature(declaration); @@ -4484,7 +4483,7 @@ namespace ts { } if (i === 0 && paramSymbol.name === "this") { hasThisParameter = true; - thisType = param.type ? getTypeFromTypeNode(param.type) : unknownType; + thisParameter = param.symbol; } else { parameters.push(paramSymbol); @@ -4508,10 +4507,12 @@ namespace ts { // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation if ((declaration.kind === SyntaxKind.GetAccessor || declaration.kind === SyntaxKind.SetAccessor) && !hasDynamicName(declaration) && - (!hasThisParameter || thisType === unknownType)) { + (!hasThisParameter || !thisParameter)) { const otherKind = declaration.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; - const setter = getDeclarationOfKind(declaration.symbol, otherKind); - thisType = getAnnotatedAccessorThisType(setter); + const other = getDeclarationOfKind(declaration.symbol, otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } } if (minArgumentCount < 0) { @@ -4532,7 +4533,7 @@ namespace ts { createTypePredicateFromTypePredicateNode(declaration.type as TypePredicateNode) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisType, parameters, returnType, typePredicate, minArgumentCount, hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -4614,6 +4615,12 @@ namespace ts { return anyType; } + function getThisTypeOfSignature(signature: Signature): Type | undefined { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function getReturnTypeOfSignature(signature: Signature): Type { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, TypeSystemPropertyName.ResolvedReturnType)) { @@ -5465,7 +5472,7 @@ namespace ts { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } const result = createSignature(signature.declaration, freshTypeParameters, - signature.thisType && instantiateType(signature.thisType, mapper), + signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, @@ -5737,17 +5744,22 @@ namespace ts { target = getErasedSignature(target); let result = Ternary.True; - if (source.thisType && target.thisType && source.thisType !== voidType) { - // void sources are assignable to anything. - const related = compareTypes(source.thisType, target.thisType, /*reportErrors*/ false) - || compareTypes(target.thisType, source.thisType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(Diagnostics.The_this_types_of_each_signature_are_incompatible); + + const sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + const targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + // void sources are assignable to anything. + const related = compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return Ternary.False; } - return Ternary.False; + result &= related; } - result &= related; } const sourceMax = getNumNonRestParameters(source); @@ -6762,13 +6774,21 @@ namespace ts { source = getErasedSignature(source); target = getErasedSignature(target); let result = Ternary.True; - if (!ignoreThisTypes && source.thisType && target.thisType) { - const related = compareTypes(source.thisType, target.thisType); - if (!related) { - return Ternary.False; + + if (!ignoreThisTypes) { + const sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + const targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + const related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return Ternary.False; + } + result &= related; + } } - result &= related; } + const targetLen = target.parameters.length; for (let i = 0; i < targetLen; i++) { const s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); @@ -8594,9 +8614,10 @@ namespace ts { if (type) { return type; } - const signature = getSignatureFromDeclaration(container); - if (signature.thisType) { - return signature.thisType; + + const thisType = getThisTypeOfDeclaration(container); + if (thisType) { + return thisType; } } if (isClassLike(container.parent)) { @@ -8837,7 +8858,7 @@ namespace ts { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== SyntaxKind.ArrowFunction) { const contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisType; + return getThisTypeOfSignature(contextualSignature); } } @@ -10637,10 +10658,11 @@ namespace ts { context.failedTypeParameterIndex = undefined; } - if (signature.thisType) { + const thisType = getThisTypeOfSignature(signature); + if (thisType) { const thisArgumentNode = getThisArgumentOfCall(node); const thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context, thisArgumentType, signature.thisType); + inferTypes(context, thisArgumentType, thisType); } // We perform two passes over the arguments. In the first pass we infer from all arguments, but use @@ -10716,8 +10738,8 @@ namespace ts { } function checkApplicableSignature(node: CallLikeExpression, args: Expression[], signature: Signature, relation: Map, excludeArgument: boolean[], reportErrors: boolean) { - - if (signature.thisType && signature.thisType !== voidType && node.kind !== SyntaxKind.NewExpression) { + const thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== SyntaxKind.NewExpression) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. @@ -10725,7 +10747,7 @@ namespace ts { const thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; const errorNode = reportErrors ? (thisArgumentNode || node) : undefined; const headMessage = Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, signature.thisType, relation, errorNode, headMessage)) { + if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage)) { return false; } } @@ -11444,7 +11466,7 @@ namespace ts { if (getReturnTypeOfSignature(signature) !== voidType) { error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } - if (signature.thisType === voidType) { + if (getThisTypeOfSignature(signature) === voidType) { error(node, Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); } return signature; @@ -13482,7 +13504,7 @@ namespace ts { // TypeScript 1.0 spec (April 2014): 4.5 // If both accessors include type annotations, the specified types must be identical. checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorThisType, Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } getTypeOfAccessors(getSymbolOfNode(node)); @@ -17162,6 +17184,15 @@ namespace ts { return getSymbolOfEntityNameOrPropertyAccessExpression(node); case SyntaxKind.ThisKeyword: + const container = getThisContainer(node, /*includeArrowFunctions*/ false); + if (isFunctionLike(container)) { + const sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + // fallthrough + case SyntaxKind.SuperKeyword: const type = isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; @@ -18694,7 +18725,7 @@ namespace ts { return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === SyntaxKind.GetAccessor ? 0 : 1); } - function getAccessorThisParameter(accessor: AccessorDeclaration) { + function getAccessorThisParameter(accessor: AccessorDeclaration): ParameterDeclaration { if (accessor.parameters.length === (accessor.kind === SyntaxKind.GetAccessor ? 1 : 2) && accessor.parameters[0].name.kind === SyntaxKind.Identifier && (accessor.parameters[0].name).originalKeywordKind === SyntaxKind.ThisKeyword) { diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index 5460f162935..76308c2cba4 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -3,22 +3,26 @@ "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, - "out": "../../built/local/tsc.js", - "sourceMap": true + "outFile": "../../built/local/tsc.js", + "sourceMap": true, + "declaration": true, + "stripInternal": true }, "files": [ - "types.ts", "core.ts", "sys.ts", - "diagnosticInformationMap.generated.ts", + "types.ts", "scanner.ts", "parser.ts", "utilities.ts", "binder.ts", "checker.ts", + "sourcemap.ts", + "declarationEmitter.ts", "emitter.ts", "program.ts", "commandLineParser.ts", - "tsc.ts" + "tsc.ts", + "diagnosticInformationMap.generated.ts" ] } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index f3549aa3815..cac04172a5c 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1874,7 +1874,7 @@ namespace ts { buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; } @@ -2394,7 +2394,8 @@ namespace ts { declaration: SignatureDeclaration; // Originating declaration typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic) parameters: Symbol[]; // Parameters - thisType?: Type; // type of this-type + /* @internal */ + thisParameter?: Symbol; // symbol of this-type parameter /* @internal */ resolvedReturnType: Type; // Resolved return type /* @internal */ diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 3ce21065b98..e5786f31335 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -879,13 +879,13 @@ namespace FourSlash { assert.equal(getDisplayPartsJson(actualQuickInfo.documentation), getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation")); } - public verifyRenameLocations(findInStrings: boolean, findInComments: boolean) { + public verifyRenameLocations(findInStrings: boolean, findInComments: boolean, ranges?: Range[]) { const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (renameInfo.canRename) { let references = this.languageService.findRenameLocations( this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments); - let ranges = this.getRanges(); + ranges = ranges || this.getRanges(); if (!references) { if (ranges.length !== 0) { @@ -3129,8 +3129,8 @@ namespace FourSlashInterface { this.state.verifyRenameInfoFailed(message); } - public renameLocations(findInStrings: boolean, findInComments: boolean) { - this.state.verifyRenameLocations(findInStrings, findInComments); + public renameLocations(findInStrings: boolean, findInComments: boolean, ranges?: FourSlash.Range[]) { + this.state.verifyRenameLocations(findInStrings, findInComments, ranges); } public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; }, diff --git a/src/server/protocol.d.ts b/src/server/protocol.d.ts index 73ef396a7e4..62162b3237c 100644 --- a/src/server/protocol.d.ts +++ b/src/server/protocol.d.ts @@ -904,7 +904,6 @@ declare namespace ts.server.protocol { * Arguments of a signature help request. */ export interface SignatureHelpRequestArgs extends FileLocationRequestArgs { - } /** @@ -923,6 +922,32 @@ declare namespace ts.server.protocol { body?: SignatureHelpItems; } + /** + * Synchronous request for semantic diagnostics of one file. + */ + export interface SemanticDiagnosticsSyncRequest extends FileRequest { + } + + /** + * Response object for synchronous sematic diagnostics request. + */ + export interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[]; + } + + /** + * Synchronous request for syntactic diagnostics of one file. + */ + export interface SyntacticDiagnosticsSyncRequest extends FileRequest { + } + + /** + * Response object for synchronous syntactic diagnostics request. + */ + export interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[]; + } + /** * Arguments for GeterrForProject request. */ diff --git a/src/server/session.ts b/src/server/session.ts index aafc02a2b0b..7a779383352 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -111,6 +111,8 @@ namespace ts.server { export const Formatonkey = "formatonkey"; export const Geterr = "geterr"; export const GeterrForProject = "geterrForProject"; + export const SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + export const SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; export const NavBar = "navbar"; export const Navto = "navto"; export const Occurrences = "occurrences"; @@ -130,6 +132,7 @@ namespace ts.server { namespace Errors { export const NoProject = new Error("No Project."); + export const ProjectLanguageServiceDisabled = new Error("The project's language service is disabled."); } export interface ServerHost extends ts.System { @@ -384,6 +387,27 @@ namespace ts.server { }); } + private getDiagnosticsWorker(args: protocol.FileRequestArgs, selector: (project: Project, file: string) => Diagnostic[]) { + const file = normalizePath(args.file); + const project = this.projectService.getProjectForFile(file); + if (!project) { + throw Errors.NoProject; + } + if (project.languageServiceDiabled) { + throw Errors.ProjectLanguageServiceDisabled; + } + const diagnostics = selector(project, file); + return ts.map(diagnostics, originalDiagnostic => formatDiag(file, project, originalDiagnostic)); + } + + private getSyntacticDiagnosticsSync(args: protocol.FileRequestArgs): protocol.Diagnostic[] { + return this.getDiagnosticsWorker(args, (project, file) => project.compilerService.languageService.getSyntacticDiagnostics(file)); + } + + private getSemanticDiagnosticsSync(args: protocol.FileRequestArgs): protocol.Diagnostic[] { + return this.getDiagnosticsWorker(args, (project, file) => project.compilerService.languageService.getSemanticDiagnostics(file)); + } + private getDocumentHighlights(line: number, offset: number, fileName: string, filesToSearch: string[]): protocol.DocumentHighlightsItem[] { fileName = ts.normalizePath(fileName); const project = this.projectService.getProjectForFile(fileName); @@ -1032,6 +1056,10 @@ namespace ts.server { exit() { } + private requiredResponse(response: any) { + return { response, responseRequired: true }; + } + private handlers: Map<(request: protocol.Request) => { response?: any, responseRequired?: boolean }> = { [CommandNames.Exit]: () => { this.exit(); @@ -1100,6 +1128,12 @@ namespace ts.server { const signatureHelpArgs = request.arguments; return { response: this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true }; }, + [CommandNames.SemanticDiagnosticsSync]: (request: protocol.FileRequest) => { + return this.requiredResponse(this.getSemanticDiagnosticsSync(request.arguments)); + }, + [CommandNames.SyntacticDiagnosticsSync]: (request: protocol.FileRequest) => { + return this.requiredResponse(this.getSyntacticDiagnosticsSync(request.arguments)); + }, [CommandNames.Geterr]: (request: protocol.Request) => { const geterrArgs = request.arguments; return { response: this.getDiagnostics(geterrArgs.delay, geterrArgs.files), responseRequired: false }; @@ -1123,7 +1157,7 @@ namespace ts.server { [CommandNames.Reload]: (request: protocol.Request) => { const reloadArgs = request.arguments; this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); - return {response: { reloadFinished: true }, responseRequired: true}; + return { response: { reloadFinished: true }, responseRequired: true }; }, [CommandNames.Saveto]: (request: protocol.Request) => { const savetoArgs = request.arguments; diff --git a/src/server/tsconfig.json b/src/server/tsconfig.json index 0772210cb15..0a8cfb89ab3 100644 --- a/src/server/tsconfig.json +++ b/src/server/tsconfig.json @@ -4,13 +4,16 @@ "removeComments": true, "preserveConstEnums": true, "out": "../../built/local/tsserver.js", - "sourceMap": true + "sourceMap": true, + "stripInternal": true }, "files": [ + "../services/shims.ts", + "../services/utilities.ts", "node.d.ts", "editorServices.ts", "protocol.d.ts", - "server.ts", - "session.ts" + "session.ts", + "server.ts" ] } diff --git a/src/services/services.ts b/src/services/services.ts index fd72fd40eee..492be6f1719 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -779,7 +779,7 @@ namespace ts { declaration: SignatureDeclaration; typeParameters: TypeParameter[]; parameters: Symbol[]; - thisType: Type; + thisParameter: Symbol; resolvedReturnType: Type; minArgumentCount: number; hasRestParameter: boolean; @@ -5819,17 +5819,32 @@ namespace ts { return undefined; } - if (node.kind !== SyntaxKind.Identifier && - // TODO (drosen): This should be enabled in a later release - currently breaks rename. - // node.kind !== SyntaxKind.ThisKeyword && - // node.kind !== SyntaxKind.SuperKeyword && - node.kind !== SyntaxKind.StringLiteral && - !isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - return undefined; + switch (node.kind) { + case SyntaxKind.NumericLiteral: + if (!isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + break; + } + // Fallthrough + case SyntaxKind.Identifier: + case SyntaxKind.ThisKeyword: + // case SyntaxKind.SuperKeyword: TODO:GH#9268 + case SyntaxKind.StringLiteral: + return getReferencedSymbolsForNode(node, program.getSourceFiles(), findInStrings, findInComments); } + return undefined; + } - Debug.assert(node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.NumericLiteral || node.kind === SyntaxKind.StringLiteral); - return getReferencedSymbolsForNode(node, program.getSourceFiles(), findInStrings, findInComments); + function isThis(node: Node): boolean { + switch (node.kind) { + case SyntaxKind.ThisKeyword: + // case SyntaxKind.ThisType: TODO: GH#9267 + return true; + case SyntaxKind.Identifier: + // 'this' as a parameter + return (node as Identifier).originalKeywordKind === SyntaxKind.ThisKeyword && node.parent.kind === SyntaxKind.Parameter; + default: + return false; + } } function getReferencedSymbolsForNode(node: Node, sourceFiles: SourceFile[], findInStrings: boolean, findInComments: boolean): ReferencedSymbol[] { @@ -5849,7 +5864,7 @@ namespace ts { } } - if (node.kind === SyntaxKind.ThisKeyword || node.kind === SyntaxKind.ThisType) { + if (isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles); } @@ -6384,7 +6399,7 @@ namespace ts { cancellationToken.throwIfCancellationRequested(); const node = getTouchingWord(sourceFile, position); - if (!node || (node.kind !== SyntaxKind.ThisKeyword && node.kind !== SyntaxKind.ThisType)) { + if (!node || !isThis(node)) { return; } @@ -8012,11 +8027,11 @@ namespace ts { const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); - // Can only rename an identifier. if (node) { if (node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.StringLiteral || - isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + isThis(node)) { const symbol = typeChecker.getSymbolAtLocation(node); // Only allow a symbol to be renamed if it actually has at least one declaration. diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index b5df2b5af20..50378aa64b1 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -357,8 +357,8 @@ namespace ts.SignatureHelp { } function getArgumentIndex(argumentsList: Node, node: Node) { - // The list we got back can include commas. In the presence of errors it may - // also just have nodes without commas. For example "Foo(a b c)" will have 3 + // The list we got back can include commas. In the presence of errors it may + // also just have nodes without commas. For example "Foo(a b c)" will have 3 // args without commas. We want to find what index we're at. So we count // forward until we hit ourselves, only incrementing the index if it isn't a // comma. @@ -390,8 +390,8 @@ namespace ts.SignatureHelp { // 'a' ''. So, in the case where the last child is a comma, we increase the // arg count by one to compensate. // - // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then - // we'll have: 'a' '' '' + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' // That will give us 2 non-commas. We then add one for the last comma, givin us an // arg count of 3. const listChildren = argumentsList.getChildren(); @@ -563,7 +563,7 @@ namespace ts.SignatureHelp { signatureHelpParameters = typeParameters && typeParameters.length > 0 ? map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; suffixDisplayParts.push(punctuationPart(SyntaxKind.GreaterThanToken)); const parameterParts = mapToDisplayParts(writer => - typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisType, candidateSignature.parameters, writer, invocation)); + typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation)); addRange(suffixDisplayParts, parameterParts); } else { diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 6aa7e61391b..4bf6e87d7a6 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -1,10 +1,13 @@ { "compilerOptions": { "noImplicitAny": true, - "removeComments": true, + "removeComments": false, "preserveConstEnums": true, - "out": "../../built/local/typescriptServices.js", - "sourceMap": true + "outFile": "../../built/local/typescriptServices.js", + "sourceMap": true, + "stripInternal": true, + "noResolve": false, + "declaration": true }, "files": [ "../compiler/core.ts", @@ -15,11 +18,12 @@ "../compiler/utilities.ts", "../compiler/binder.ts", "../compiler/checker.ts", + "../compiler/sourcemap.ts", + "../compiler/declarationEmitter.ts", "../compiler/emitter.ts", "../compiler/program.ts", - "../compiler/declarationEmitter.ts", - "../compiler/diagnosticInformationMap.generated.ts", "../compiler/commandLineParser.ts", + "../compiler/diagnosticInformationMap.generated.ts", "breakpoints.ts", "navigateTo.ts", "navigationBar.ts", diff --git a/tests/baselines/reference/inferParameterWithMethodCallInitializer.symbols b/tests/baselines/reference/inferParameterWithMethodCallInitializer.symbols index e0734a4b39b..ce098f6e243 100644 --- a/tests/baselines/reference/inferParameterWithMethodCallInitializer.symbols +++ b/tests/baselines/reference/inferParameterWithMethodCallInitializer.symbols @@ -30,7 +30,7 @@ function weird(this: Example, a = this.getNumber()) { >Example : Symbol(Example, Decl(inferParameterWithMethodCallInitializer.ts, 2, 1)) >a : Symbol(a, Decl(inferParameterWithMethodCallInitializer.ts, 11, 29)) >this.getNumber : Symbol(Example.getNumber, Decl(inferParameterWithMethodCallInitializer.ts, 3, 15)) ->this : Symbol(Example, Decl(inferParameterWithMethodCallInitializer.ts, 2, 1)) +>this : Symbol(this, Decl(inferParameterWithMethodCallInitializer.ts, 11, 15)) >getNumber : Symbol(Example.getNumber, Decl(inferParameterWithMethodCallInitializer.ts, 3, 15)) return a; @@ -45,7 +45,7 @@ class Weird { >Example : Symbol(Example, Decl(inferParameterWithMethodCallInitializer.ts, 2, 1)) >a : Symbol(a, Decl(inferParameterWithMethodCallInitializer.ts, 15, 30)) >this.getNumber : Symbol(Example.getNumber, Decl(inferParameterWithMethodCallInitializer.ts, 3, 15)) ->this : Symbol(Example, Decl(inferParameterWithMethodCallInitializer.ts, 2, 1)) +>this : Symbol(this, Decl(inferParameterWithMethodCallInitializer.ts, 15, 16)) >getNumber : Symbol(Example.getNumber, Decl(inferParameterWithMethodCallInitializer.ts, 3, 15)) return a; diff --git a/tests/baselines/reference/thisTypeInAccessors.symbols b/tests/baselines/reference/thisTypeInAccessors.symbols index ef2201d3808..a68341dfc14 100644 --- a/tests/baselines/reference/thisTypeInAccessors.symbols +++ b/tests/baselines/reference/thisTypeInAccessors.symbols @@ -20,7 +20,7 @@ const explicit = { >this : Symbol(this, Decl(thisTypeInAccessors.ts, 7, 10)) >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 7, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) set x(this: Foo, n: number) { this.n = n; } @@ -29,7 +29,7 @@ const explicit = { >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 8, 20)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 8, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 8, 20)) } @@ -44,14 +44,14 @@ const copiedFromGetter = { >this : Symbol(this, Decl(thisTypeInAccessors.ts, 12, 10)) >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 12, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) set x(n) { this.n = n; } >x : Symbol(x, Decl(thisTypeInAccessors.ts, 11, 10), Decl(thisTypeInAccessors.ts, 12, 48)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 13, 10)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 12, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 13, 10)) } @@ -64,7 +64,7 @@ const copiedFromSetter = { get x() { return this.n }, >x : Symbol(x, Decl(thisTypeInAccessors.ts, 16, 10), Decl(thisTypeInAccessors.ts, 17, 30)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 18, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) set x(this: Foo, n: number) { this.n = n; } @@ -73,7 +73,7 @@ const copiedFromSetter = { >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 18, 20)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 18, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 18, 20)) } @@ -88,7 +88,7 @@ const copiedFromGetterUnannotated = { >this : Symbol(this, Decl(thisTypeInAccessors.ts, 22, 10)) >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 22, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) set x(this, n) { this.n = n; } @@ -96,7 +96,7 @@ const copiedFromGetterUnannotated = { >this : Symbol(this, Decl(thisTypeInAccessors.ts, 23, 10)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 23, 15)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 23, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 23, 15)) } @@ -112,7 +112,7 @@ class Explicit { >this : Symbol(this, Decl(thisTypeInAccessors.ts, 28, 10)) >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 28, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) set x(this: Foo, n: number) { this.n = n; } @@ -121,7 +121,7 @@ class Explicit { >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 29, 20)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 29, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 29, 20)) } diff --git a/tests/baselines/reference/thisTypeInFunctions.symbols b/tests/baselines/reference/thisTypeInFunctions.symbols index 3d4c3f6ecc7..8a0be7427ed 100644 --- a/tests/baselines/reference/thisTypeInFunctions.symbols +++ b/tests/baselines/reference/thisTypeInFunctions.symbols @@ -19,7 +19,7 @@ class C { return this.n + m; >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 6, 17)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 6, 28)) } @@ -31,7 +31,7 @@ class C { return this.n + m; >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 9, 14)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 9, 22)) } @@ -43,7 +43,7 @@ class C { return this.n + m; >this.n : Symbol(n, Decl(thisTypeInFunctions.ts, 12, 28)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 12, 26)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 12, 21)) >n : Symbol(n, Decl(thisTypeInFunctions.ts, 12, 28)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 12, 39)) } @@ -97,7 +97,7 @@ function explicitStructural(this: { y: number }, x: number): number { return x + this.y; >x : Symbol(x, Decl(thisTypeInFunctions.ts, 28, 48)) >this.y : Symbol(y, Decl(thisTypeInFunctions.ts, 28, 35)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 28, 33)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 28, 28)) >y : Symbol(y, Decl(thisTypeInFunctions.ts, 28, 35)) } function justThis(this: { y: number }): number { @@ -107,7 +107,7 @@ function justThis(this: { y: number }): number { return this.y; >this.y : Symbol(y, Decl(thisTypeInFunctions.ts, 31, 25)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 31, 23)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 31, 18)) >y : Symbol(y, Decl(thisTypeInFunctions.ts, 31, 25)) } function implicitThis(n: number): number { @@ -435,7 +435,7 @@ c.explicitC = function(this: C, m: number) { return this.n + m }; >C : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 105, 31)) >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 105, 23)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 105, 31)) @@ -453,7 +453,7 @@ c.explicitProperty = function(this: {n: number}, m: number) { return this.n + m >n : Symbol(n, Decl(thisTypeInFunctions.ts, 107, 37)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 107, 48)) >this.n : Symbol(n, Decl(thisTypeInFunctions.ts, 107, 37)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 107, 35)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 107, 30)) >n : Symbol(n, Decl(thisTypeInFunctions.ts, 107, 37)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 107, 48)) @@ -525,7 +525,7 @@ c.explicitThis = function(this: C, m: number) { return this.n + m }; >C : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 123, 34)) >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 123, 26)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 123, 34)) @@ -568,7 +568,7 @@ c.explicitThis = function(this, m) { return this.n + m }; >this : Symbol(this, Decl(thisTypeInFunctions.ts, 131, 26)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 131, 31)) >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 131, 26)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 131, 31)) @@ -581,7 +581,7 @@ c.explicitC = function(this: B, m: number) { return this.n + m }; >B : Symbol(B, Decl(thisTypeInFunctions.ts, 0, 0)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 134, 31)) >this.n : Symbol(B.n, Decl(thisTypeInFunctions.ts, 1, 9)) ->this : Symbol(B, Decl(thisTypeInFunctions.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 134, 23)) >n : Symbol(B.n, Decl(thisTypeInFunctions.ts, 1, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 134, 31)) @@ -604,7 +604,7 @@ class Base1 { >polymorphic : Symbol(Base1.polymorphic, Decl(thisTypeInFunctions.ts, 141, 14)) >this : Symbol(this, Decl(thisTypeInFunctions.ts, 142, 23)) >this.x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) ->this : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 142, 23)) >x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) explicit(this: Base1): number { return this.x; } @@ -612,7 +612,7 @@ class Base1 { >this : Symbol(this, Decl(thisTypeInFunctions.ts, 143, 13)) >Base1 : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) >this.x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) ->this : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 143, 13)) >x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) static explicitStatic(this: typeof Base1): number { return this.y; } @@ -620,7 +620,7 @@ class Base1 { >this : Symbol(this, Decl(thisTypeInFunctions.ts, 144, 26)) >Base1 : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) >this.y : Symbol(Base1.y, Decl(thisTypeInFunctions.ts, 144, 72)) ->this : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 144, 26)) >y : Symbol(Base1.y, Decl(thisTypeInFunctions.ts, 144, 72)) static y: number; @@ -643,7 +643,7 @@ class Base2 { >polymorphic : Symbol(Base2.polymorphic, Decl(thisTypeInFunctions.ts, 151, 13)) >this : Symbol(this, Decl(thisTypeInFunctions.ts, 152, 16)) >this.y : Symbol(Base2.y, Decl(thisTypeInFunctions.ts, 150, 13)) ->this : Symbol(Base2, Decl(thisTypeInFunctions.ts, 149, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 152, 16)) >y : Symbol(Base2.y, Decl(thisTypeInFunctions.ts, 150, 13)) explicit(this: Base1): number { return this.x; } @@ -651,7 +651,7 @@ class Base2 { >this : Symbol(this, Decl(thisTypeInFunctions.ts, 153, 13)) >Base1 : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) >this.x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) ->this : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 153, 13)) >x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) } class Derived2 extends Base2 { @@ -734,7 +734,7 @@ function InterfaceThis(this: I) { this.a = 12; >this.a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) ->this : Symbol(I, Decl(thisTypeInFunctions.ts, 19, 21)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 172, 23)) >a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) } function LiteralTypeThis(this: {x: string}) { @@ -744,7 +744,7 @@ function LiteralTypeThis(this: {x: string}) { this.x = "ok"; >this.x : Symbol(x, Decl(thisTypeInFunctions.ts, 175, 32)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 175, 30)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 175, 25)) >x : Symbol(x, Decl(thisTypeInFunctions.ts, 175, 32)) } function AnyThis(this: any) { @@ -752,6 +752,7 @@ function AnyThis(this: any) { >this : Symbol(this, Decl(thisTypeInFunctions.ts, 178, 17)) this.x = "ok"; +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 178, 17)) } let interfaceThis = new InterfaceThis(); >interfaceThis : Symbol(interfaceThis, Decl(thisTypeInFunctions.ts, 181, 3)) @@ -793,5 +794,6 @@ function missingTypeIsImplicitAny(this, a: number) { return this.anything + a; } >missingTypeIsImplicitAny : Symbol(missingTypeIsImplicitAny, Decl(thisTypeInFunctions.ts, 190, 27)) >this : Symbol(this, Decl(thisTypeInFunctions.ts, 192, 34)) >a : Symbol(a, Decl(thisTypeInFunctions.ts, 192, 39)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 192, 34)) >a : Symbol(a, Decl(thisTypeInFunctions.ts, 192, 39)) diff --git a/tests/baselines/reference/thisTypeInFunctions.types b/tests/baselines/reference/thisTypeInFunctions.types index ddef8544a54..24c4fb87baf 100644 --- a/tests/baselines/reference/thisTypeInFunctions.types +++ b/tests/baselines/reference/thisTypeInFunctions.types @@ -692,11 +692,11 @@ c.explicitThis = function(m) { return this.n + m }; // this: contextual typing c.explicitThis = function(this, m) { return this.n + m }; ->c.explicitThis = function(this, m) { return this.n + m } : (this: any, m: number) => number +>c.explicitThis = function(this, m) { return this.n + m } : (this: C, m: number) => number >c.explicitThis : (this: C, m: number) => number >c : C >explicitThis : (this: C, m: number) => number ->function(this, m) { return this.n + m } : (this: any, m: number) => number +>function(this, m) { return this.n + m } : (this: C, m: number) => number >this : C >m : number >this.n + m : number diff --git a/tests/cases/fourslash/findAllRefsThisKeyword.ts b/tests/cases/fourslash/findAllRefsThisKeyword.ts new file mode 100644 index 00000000000..f08a70ccf65 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsThisKeyword.ts @@ -0,0 +1,33 @@ +/// +// @noLib: true + +////[|this|]; +////function f([|this|]) { +//// return [|this|]; +//// function g([|this|]) { return [|this|]; } +////} +////class C { +//// static x() { +//// [|this|]; +//// } +//// static y() { +//// () => [|this|]; +//// } +//// constructor() { +//// [|this|]; +//// } +//// method() { +//// () => [|this|]; +//// } +////} +////// These are *not* real uses of the 'this' keyword, they are identifiers. +////const x = { [|this|]: 0 } +////x.[|this|]; + +const [global, f0, f1, g0, g1, x, y, constructor, method, propDef, propUse] = test.ranges(); +verify.referencesOf(global, [global]); +verify.rangesReferenceEachOther([f0, f1]); +verify.rangesReferenceEachOther([g0, g1]); +verify.rangesReferenceEachOther([x, y]); +verify.rangesReferenceEachOther([constructor, method]); +verify.rangesReferenceEachOther([propDef, propUse]); diff --git a/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts b/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts index 873324fae21..a4bab7f876c 100644 --- a/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts +++ b/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts @@ -1,18 +1,15 @@ /// // @Filename: file1.ts -////this; this; +////[|this|]; [|this|]; // @Filename: file2.ts -////this; -////this; +////[|this|]; +////[|this|]; // @Filename: file3.ts -//// ((x = this, y) => t/**/his)(this, this); +//// ((x = [|this|], y) => [|this|])([|this|], [|this|]); +//// // different 'this' +//// function f(this) { return this; } -goTo.file("file1.ts"); -goTo.marker(); - -// TODO (drosen): The CURRENT behavior is that findAllRefs doesn't work on 'this' or 'super' keywords. -// This should change down the line. -verify.referencesAre([]); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index c7803a023ef..9cb816a13bd 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -217,7 +217,7 @@ declare namespace FourSlashInterface { }[]): void; renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string): void; renameInfoFailed(message?: string): void; - renameLocations(findInStrings: boolean, findInComments: boolean): void; + renameLocations(findInStrings: boolean, findInComments: boolean, ranges?: Range[]): void; verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; diff --git a/tests/cases/fourslash/goToDefinitionThis.ts b/tests/cases/fourslash/goToDefinitionThis.ts new file mode 100644 index 00000000000..300e3423d81 --- /dev/null +++ b/tests/cases/fourslash/goToDefinitionThis.ts @@ -0,0 +1,20 @@ +/// + +// @noLib: true +////function f(/*fnDecl*/this: number) { +//// return /*fnUse*/this; +////} +/////*cls*/class C { +//// constructor() { return /*clsUse*/this; } +//// get self(/*getterDecl*/this: number) { return /*getterUse*/this; } +////} + +function verifyDefinition(a, b) { + goTo.marker(a); + goTo.definition(); + verify.caretAtMarker(b); +} + +verifyDefinition("fnUse", "fnDecl"); +verifyDefinition("clsUse", "cls"); +verifyDefinition("getterUse", "getterDecl"); diff --git a/tests/cases/fourslash/quickInfoOnThis.ts b/tests/cases/fourslash/quickInfoOnThis.ts index 4191c0846ec..14737486b87 100644 --- a/tests/cases/fourslash/quickInfoOnThis.ts +++ b/tests/cases/fourslash/quickInfoOnThis.ts @@ -25,7 +25,7 @@ goTo.marker('0'); verify.quickInfoIs('this: this'); goTo.marker('1'); -verify.quickInfoIs('void'); +verify.quickInfoIs('this: void'); goTo.marker('2'); verify.quickInfoIs('this: this'); goTo.marker('3'); diff --git a/tests/cases/fourslash/quickInfoOnThis3.ts b/tests/cases/fourslash/quickInfoOnThis3.ts index 6988ac14860..239e49d5dc0 100644 --- a/tests/cases/fourslash/quickInfoOnThis3.ts +++ b/tests/cases/fourslash/quickInfoOnThis3.ts @@ -20,7 +20,7 @@ verify.quickInfoIs('any'); goTo.marker('2'); verify.quickInfoIs('(parameter) this: void'); goTo.marker('3'); -verify.quickInfoIs('void'); +verify.quickInfoIs('this: void'); goTo.marker('4'); verify.quickInfoIs('(parameter) this: Restricted'); goTo.marker('5'); diff --git a/tests/cases/fourslash/renameThis.ts b/tests/cases/fourslash/renameThis.ts new file mode 100644 index 00000000000..f567cace70d --- /dev/null +++ b/tests/cases/fourslash/renameThis.ts @@ -0,0 +1,22 @@ +/// + +////function f([|this|]) { +//// return [|this|]; +////} +////this/**/; +////const _ = { [|this|]: 0 }.[|this|]; + +let [r0, r1, r2, r3] = test.ranges() +for (let range of [r0, r1]) { + goTo.position(range.start); + verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, [r0, r1]); +} + +// Trying to rename a non-parameter 'this' should fail +goTo.marker(); +verify.renameInfoFailed("You cannot rename this element."); + +for (let range of [r2, r3]) { + goTo.position(range.start); + verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, [r2, r3]); +} diff --git a/tests/cases/unittests/moduleResolution.ts b/tests/cases/unittests/moduleResolution.ts index 16fc7df8d70..70cb4715c48 100644 --- a/tests/cases/unittests/moduleResolution.ts +++ b/tests/cases/unittests/moduleResolution.ts @@ -589,7 +589,7 @@ import b = require("./moduleB.ts"); const file1: File = { name: "/root/folder1/file1.ts" }; const file2: File = { name: "/root/generated/folder1/file2.ts" }; // load remapped file as module const file3: File = { name: "/root/generated/folder2/file3/index.d.ts" }; // load folder a module - const file4Typings: File = { name: "/root/generated/folder2/file4/package.json", content: JSON.stringify({ typings: "dist/types.d.ts" })}; + const file4Typings: File = { name: "/root/generated/folder2/file4/package.json", content: JSON.stringify({ typings: "dist/types.d.ts" }) }; const file4: File = { name: "/root/generated/folder2/file4/dist/types.d.ts" }; // load file pointed by typings const file5: File = { name: "/root/someanotherfolder/file5/index.d.ts" }; // load remapped module from folder const file6: File = { name: "/root/node_modules/file6.ts" }; // fallback to node @@ -957,7 +957,7 @@ import b = require("./moduleB.ts"); describe("Type reference directive resolution: ", () => { function test(typesRoot: string, typeDirective: string, primary: boolean, initialFile: File, targetFile: File, ...otherFiles: File[]) { const host = createModuleResolutionHost(/*hasDirectoryExists*/ false, ...[initialFile, targetFile].concat(...otherFiles)); - const result = resolveTypeReferenceDirective(typeDirective, initialFile.name, {typeRoots: [typesRoot]}, host); + const result = resolveTypeReferenceDirective(typeDirective, initialFile.name, { typeRoots: [typesRoot] }, host); assert(result.resolvedTypeReferenceDirective.resolvedFileName !== undefined, "expected type directive to be resolved"); assert.equal(result.resolvedTypeReferenceDirective.resolvedFileName, targetFile.name, "unexpected result of type reference resolution"); assert.equal(result.resolvedTypeReferenceDirective.primary, primary, "unexpected 'primary' value"); @@ -972,7 +972,7 @@ import b = require("./moduleB.ts"); { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/types/lib/typings/lib.d.ts" }; - const package = { name: "/root/src/types/lib/package.json", content: JSON.stringify({types: "typings/lib.d.ts"}) }; + const package = { name: "/root/src/types/lib/package.json", content: JSON.stringify({ types: "typings/lib.d.ts" }) }; test(/*typesRoot*/"/root/src/types", /* typeDirective */"lib", /*primary*/ true, f1, f2, package); } { @@ -983,7 +983,7 @@ import b = require("./moduleB.ts"); { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/node_modules/lib/typings/lib.d.ts" }; - const package = { name: "/root/src/node_modules/lib/package.json", content: JSON.stringify({types: "typings/lib.d.ts"}) }; + const package = { name: "/root/src/node_modules/lib/package.json", content: JSON.stringify({ types: "typings/lib.d.ts" }) }; test(/*typesRoot*/"/root/src/types", /* typeDirective */"lib", /*primary*/ false, f1, f2, package); } { @@ -994,7 +994,7 @@ import b = require("./moduleB.ts"); { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/node_modules/@types/lib/typings/lib.d.ts" }; - const package = { name: "/root/src/node_modules/@types/lib/package.json", content: JSON.stringify({types: "typings/lib.d.ts"}) }; + const package = { name: "/root/src/node_modules/@types/lib/package.json", content: JSON.stringify({ types: "typings/lib.d.ts" }) }; test(/*typesRoot*/"/root/src/types", /* typeDirective */"lib", /*primary*/ false, f1, f2, package); } }); @@ -1012,7 +1012,7 @@ import b = require("./moduleB.ts"); { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/node_modules/lib/typings/lib.d.ts" }; - const package = { name: "/root/node_modules/lib/package.json", content: JSON.stringify({typings: "typings/lib.d.ts"}) }; + const package = { name: "/root/node_modules/lib/package.json", content: JSON.stringify({ typings: "typings/lib.d.ts" }) }; test(/*typesRoot*/"/root/src/types", /* typeDirective */"lib", /*primary*/ false, f1, f2, package); } { @@ -1023,7 +1023,7 @@ import b = require("./moduleB.ts"); { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/node_modules/@types/lib/typings/lib.d.ts" }; - const package = { name: "/root/node_modules/@types/lib/package.json", content: JSON.stringify({typings: "typings/lib.d.ts"}) }; + const package = { name: "/root/node_modules/@types/lib/package.json", content: JSON.stringify({ typings: "typings/lib.d.ts" }) }; test(/*typesRoot*/"/root/src/types", /* typeDirective */"lib", /*primary*/ false, f1, f2, package); } }); diff --git a/tests/cases/unittests/session.ts b/tests/cases/unittests/session.ts index a2edb05b39b..b9073365d91 100644 --- a/tests/cases/unittests/session.ts +++ b/tests/cases/unittests/session.ts @@ -170,7 +170,7 @@ namespace ts.server { describe("send", () => { it("is an overrideable handle which sends protocol messages over the wire", () => { - const msg = {seq: 0, type: "none"}; + const msg = { seq: 0, type: "none" }; const strmsg = JSON.stringify(msg); const len = 1 + Utils.byteLength(strmsg, "utf8"); const resultMsg = `Content-Length: ${len}\r\n\r\n${strmsg}\n`; @@ -266,7 +266,7 @@ namespace ts.server { constructor() { super(mockHost, Utils.byteLength, process.hrtime, mockLogger); this.addProtocolHandler(this.customHandler, () => { - return {response: undefined, responseRequired: true}; + return { response: undefined, responseRequired: true }; }); } send(msg: protocol.Message) { @@ -340,7 +340,7 @@ namespace ts.server { handleRequest(msg: protocol.Request) { let response: protocol.Response; try { - ({response} = this.executeCommand(msg)); + ({ response } = this.executeCommand(msg)); } catch (e) { this.output(undefined, msg.command, msg.seq, e.toString()); diff --git a/tests/cases/unittests/transpile.ts b/tests/cases/unittests/transpile.ts index 5900a29bb5d..206f69142a5 100644 --- a/tests/cases/unittests/transpile.ts +++ b/tests/cases/unittests/transpile.ts @@ -239,195 +239,195 @@ var x = 0;`, { }); transpilesCorrectly("Supports setting 'allowJs'", "x;", { - options: { compilerOptions: { allowJs: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { allowJs: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'allowSyntheticDefaultImports'", "x;", { - options: { compilerOptions: { allowSyntheticDefaultImports: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { allowSyntheticDefaultImports: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'allowUnreachableCode'", "x;", { - options: { compilerOptions: { allowUnreachableCode: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { allowUnreachableCode: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'allowUnusedLabels'", "x;", { - options: { compilerOptions: { allowUnusedLabels: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { allowUnusedLabels: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'baseUrl'", "x;", { - options: { compilerOptions: { baseUrl: "./folder/baseUrl" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { baseUrl: "./folder/baseUrl" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'charset'", "x;", { - options: { compilerOptions: { charset: "en-us" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { charset: "en-us" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'declaration'", "x;", { - options: { compilerOptions: { declaration: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { declaration: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'declarationDir'", "x;", { - options: { compilerOptions: { declarationDir: "out/declarations" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { declarationDir: "out/declarations" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'emitBOM'", "x;", { - options: { compilerOptions: { emitBOM: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { emitBOM: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'emitDecoratorMetadata'", "x;", { - options: { compilerOptions: { emitDecoratorMetadata: true, experimentalDecorators: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { emitDecoratorMetadata: true, experimentalDecorators: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'experimentalDecorators'", "x;", { - options: { compilerOptions: { experimentalDecorators: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { experimentalDecorators: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'forceConsistentCasingInFileNames'", "x;", { - options: { compilerOptions: { forceConsistentCasingInFileNames: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { forceConsistentCasingInFileNames: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'isolatedModules'", "x;", { - options: { compilerOptions: { isolatedModules: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { isolatedModules: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'jsx'", "x;", { - options: { compilerOptions: { jsx: 1 }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { jsx: 1 }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'lib'", "x;", { - options: { compilerOptions: { lib: ["es2015", "dom"] }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { lib: ["es2015", "dom"] }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'locale'", "x;", { - options: { compilerOptions: { locale: "en-us" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { locale: "en-us" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'module'", "x;", { - options: { compilerOptions: { module: ModuleKind.CommonJS }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { module: ModuleKind.CommonJS }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'moduleResolution'", "x;", { - options: { compilerOptions: { moduleResolution: ModuleResolutionKind.NodeJs }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { moduleResolution: ModuleResolutionKind.NodeJs }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'newLine'", "x;", { - options: { compilerOptions: { newLine: NewLineKind.CarriageReturnLineFeed }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { newLine: NewLineKind.CarriageReturnLineFeed }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noEmit'", "x;", { - options: { compilerOptions: { noEmit: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noEmit: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noEmitHelpers'", "x;", { - options: { compilerOptions: { noEmitHelpers: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noEmitHelpers: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noEmitOnError'", "x;", { - options: { compilerOptions: { noEmitOnError: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noEmitOnError: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noErrorTruncation'", "x;", { - options: { compilerOptions: { noErrorTruncation: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noErrorTruncation: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noFallthroughCasesInSwitch'", "x;", { - options: { compilerOptions: { noFallthroughCasesInSwitch: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noFallthroughCasesInSwitch: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noImplicitAny'", "x;", { - options: { compilerOptions: { noImplicitAny: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noImplicitAny: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noImplicitReturns'", "x;", { - options: { compilerOptions: { noImplicitReturns: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noImplicitReturns: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noImplicitThis'", "x;", { - options: { compilerOptions: { noImplicitThis: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noImplicitThis: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noImplicitUseStrict'", "x;", { - options: { compilerOptions: { noImplicitUseStrict: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noImplicitUseStrict: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noLib'", "x;", { - options: { compilerOptions: { noLib: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noLib: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noResolve'", "x;", { - options: { compilerOptions: { noResolve: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noResolve: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'out'", "x;", { - options: { compilerOptions: { out: "./out" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { out: "./out" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'outDir'", "x;", { - options: { compilerOptions: { outDir: "./outDir" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { outDir: "./outDir" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'outFile'", "x;", { - options: { compilerOptions: { outFile: "./outFile" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { outFile: "./outFile" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'paths'", "x;", { - options: { compilerOptions: { paths: { "*": ["./generated*"] } }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { paths: { "*": ["./generated*"] } }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'preserveConstEnums'", "x;", { - options: { compilerOptions: { preserveConstEnums: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { preserveConstEnums: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'reactNamespace'", "x;", { - options: { compilerOptions: { reactNamespace: "react" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { reactNamespace: "react" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'removeComments'", "x;", { - options: { compilerOptions: { removeComments: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { removeComments: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'rootDir'", "x;", { - options: { compilerOptions: { rootDir: "./rootDir" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { rootDir: "./rootDir" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'rootDirs'", "x;", { - options: { compilerOptions: { rootDirs: ["./a", "./b"] }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { rootDirs: ["./a", "./b"] }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'skipLibCheck'", "x;", { - options: { compilerOptions: { skipLibCheck: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { skipLibCheck: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'skipDefaultLibCheck'", "x;", { - options: { compilerOptions: { skipDefaultLibCheck: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { skipDefaultLibCheck: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'strictNullChecks'", "x;", { - options: { compilerOptions: { strictNullChecks: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { strictNullChecks: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'stripInternal'", "x;", { - options: { compilerOptions: { stripInternal: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { stripInternal: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'suppressExcessPropertyErrors'", "x;", { - options: { compilerOptions: { suppressExcessPropertyErrors: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { suppressExcessPropertyErrors: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'suppressImplicitAnyIndexErrors'", "x;", { - options: { compilerOptions: { suppressImplicitAnyIndexErrors: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { suppressImplicitAnyIndexErrors: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'target'", "x;", { - options: { compilerOptions: { target: 2 }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { target: 2 }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'types'", "x;", { - options: { compilerOptions: { types: ["jquery", "jasmine"] }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { types: ["jquery", "jasmine"] }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'typeRoots'", "x;", { - options: { compilerOptions: { typeRoots: ["./folder"] }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { typeRoots: ["./folder"] }, fileName: "input.js", reportDiagnostics: true } }); }); } diff --git a/tslint.json b/tslint.json index f789af46cea..ee116c6fcb0 100644 --- a/tslint.json +++ b/tslint.json @@ -44,6 +44,7 @@ "type-operator-spacing": true, "prefer-const": true, "no-in-operator": true, - "no-increment-decrement": true + "no-increment-decrement": true, + "object-literal-surrounding-space": true } }